Regex 如何用2个组替换正则表达式
我的正则表达式有问题。 我的代码是:Regex 如何用2个组替换正则表达式,regex,python-3.x,regex-group,Regex,Python 3.x,Regex Group,我的正则表达式有问题。 我的代码是: self.file = re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])',r'\1\2',self.file) 我需要替换这个: TJumpMatchArray *skipTableMatch ); void computeCharJumps(string *str 为此: TJumpMatchArray *skipTableMatch ); void computeCha
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
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")
我需要存储空白,并且需要替换所有不在{}之后的新行“\n”;带有“”
我发现问题可能是python解释(使用python 3.2.3)无法并行工作,如果它与第一组不匹配,则会失败:
TJumpMatchArray *skipTableMatch );
void computeCharJumps(string *str
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")
因为如果我有:
'; \n'
它取代了:
' \n'
我需要在{};之后存储相同的格式
有办法解决这个问题吗 问题是,对于每个找到的匹配,只有一个组不是空的 考虑这个简化的例子:
>>> import re
>>>
>>> def replace(match):
... print(match.groups())
... return "X"
...
>>> re.sub("(a)|(b)", replace, "-ab-")
('a', None)
(None, 'b')
'-XX-'
如您所见,replacement函数被调用两次,一次是第二个组设置为None
,一次是第一个组
如果要使用函数替换匹配项(如我的示例中),可以很容易地检查哪些组是匹配的组
例如:
re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])', lambda m: m.group(1) or m.group(2), self.file)
如果您只需搜索
(\w+)\n
并替换为\1
,它会工作吗?但它会替换'\而且我不想;)不,它不会,因为\w
与不匹配代码>。您需要在哪里匹配()
?我只使用了您示例中的内容:{1}
也是冗余的,[\n]
与\n
相同。这正是我需要的:)!(对于此:)