【问题标题】:How to replace regex with 2 groups如何用 2 组替换正则表达式
【发布时间】: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


【解决方案1】:

问题在于,对于每个找到的匹配项,只有一组不是空的。

考虑这个简化的例子:

>>> import re
>>> 
>>> def replace(match):
...     print(match.groups())
...     return "X"
... 
>>> re.sub("(a)|(b)", replace, "-ab-")
('a', None)
(None, 'b')
'-XX-'

如您所见,替换函数被调用了两次,一次将第二组设置为None,一次使用第一个。

如果您要使用函数替换匹配项(如我的示例中所示),您可以轻松检查哪些组是匹配组。

例子:

re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])', lambda m: m.group(1) or m.group(2), self.file)

【讨论】:

  • 这正是我需要的:)! Ty :)
猜你喜欢
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2014-01-25
  • 1970-01-01
  • 2015-07-25
  • 2012-08-01
相关资源
最近更新 更多