Python Regex 立即替换组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14007545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:09:49  来源:igfitidea点击:

Python Regex instantly replace groups

pythonregexregex-group

提问by

Is there any way to directly replace all groups using regex syntax?

有没有办法使用正则表达式直接替换所有组?

The normal way:

正常方式:

re.match(r"(?:aaa)(_bbb)", string1).group(1)

But I want to achieve something like this:

但我想实现这样的目标:

re.match(r"(\d.*?)\s(\d.*?)", "(CALL_GROUP_1) (CALL_GROUP_2)")

I want to build the new string instantaneously from the groups the Regex just captured.

我想从 Regex 刚刚捕获的组中立即构建新字符串。

采纳答案by Martin Ender

Have a look at re.sub:

看看re.sub

result = re.sub(r"(\d.*?)\s(\d.*?)", r" ", string1)

This is Python's regex substitution (replace) function. The replacement string can be filled with so-called backreferences (backslash, group number) which are replaced with what was matched by the groups. Groups are counted the same as by the group(...)function, i.e. starting from 1, from left to right, by opening parentheses.

这是 Python 的正则表达式替换(replace)函数。替换字符串可以用所谓的反向引用(反斜杠、组号)填充,这些引用被组匹配的内容替换。组的计数与group(...)函数相同,即从 开始1,从左到右,通过左括号。

回答by benelgiac

The accepted answer is perfect. I would add that group reference is probably better achieved by using this syntax:

接受的答案是完美的。我会补充说,使用以下语法可能会更好地实现组引用:

r"\g<1> \g<2>"

for the replacement string. This way, you work around syntax limitations where a group may be followed by a digit. Again, this is all present in the doc, nothing new, just sometimes difficult to spot at first sight.

对于替换字符串。通过这种方式,您可以解决组后面可能跟数字的语法限制。同样,这一切都出现在文档中,没有什么新东西,只是有时乍一看很难发现。