【发布时间】:2014-04-11 20:39:40
【问题描述】:
我在 REGEX 中遇到问题。 我的代码是:
self.file = re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])',r'\1\2',self.file)
我需要更换这个:
TJumpMatchArray *skipTableMatch
);
void computeCharJumps(string *str
用这个:
TJumpMatchArray *skipTableMatch );
void computeCharJumps(string *str
我需要存储空格并且我需要替换所有不在 {} 之后的新行 '\n';和 '' 。
我发现问题可能是 python 解释(使用 Python 3.2.3)不能正常工作,如果它与第一组不匹配,如果失败:
File "cha.py", line 142, in <module>
maker.editFileContent()
File "cha.py", line 129, in editFileContent
self.file = re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])',r'\1|\2',self.file)
File "/usr/local/lib/python3.2/re.py", line 167, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/local/lib/python3.2/re.py", line 286, in filter
return sre_parse.expand_template(template, match)
File "/usr/local/lib/python3.2/sre_parse.py", line 813, in expand_template
raise error("unmatched group")
在这个在线正则表达式工具中它正在工作:Example here
我使用的原因:
|([;{}]\s*[\n])
是因为如果我有:
'; \n'
它取代了:
' \n'
带 '' 并且我需要在 {}; 之后存储相同的格式。
有没有办法解决这个问题?
【问题讨论】:
-
如果你只搜索
(\w +)\n并替换为\1,它会起作用吗? -
但它会替换 '; \n',我不想;)
-
不,它不会,因为
\w不匹配;。 -
哪里需要匹配
()?我只使用了您的示例中的内容:regex101.com/r/xE5bV2 -
另外
{1}是多余的,[\n]与\n相同。
标签: regex python-3.x regex-group