[英]Python regex: Replace individual characters in a match
I'm trying to substitute every individual character found in a regex match but I can't seem to make it work. 我正在尝试替换正则表达式匹配项中找到的每个字符,但似乎无法使其正常工作。
I have a string containing parenthesized expressions that have to be replaced. 我有一个字符串,其中包含必须替换的带括号的表达式。
For example, foo bar (baz)
should become foo bar (***)
例如,
foo bar (baz)
应该变成foo bar (***)
Here is what I came up with: re.sub(r"(\\(.*?).(.*?\\))", r"\\1*\\2", "foo bar (baz)")
Unfortunately, I can't seem to apply the substitution to every character between the parentheses. 这是我想出的:
re.sub(r"(\\(.*?).(.*?\\))", r"\\1*\\2", "foo bar (baz)")
不幸的是,我似乎无法将替换应用于括号之间的每个字符。 Is there any way to make this work? 有什么办法可以使这项工作吗?
How about something like this? 这样的事情怎么样?
>>> import re
>>> s = 'foo bar (baz)'
>>> re.sub(r'(?<=\().*?(?=\))', lambda m: '*'*len(m.group()), s)
'foo bar (***)'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.