[英]Python 2.7 Regex capture groups not working as predicted
I am trying to pattern match and replace first person with second person with Python 2.7. 我正在尝试使用Python 2.7模式匹配并将第一人称替换为第二人称。
string = re.sub(r'(\W)I(\W)', '\g<1>you\g<2>',string)
string = re.sub(r'(\W)(me)(\W)', '\g<1>you\g<3>',string)
# but does NOT work
string = re.sub(r'(\W)I|(me)(\W)', '\g<1>you\g<3>',string)
I want to use the last regex, but somehow the capture groups are all messed up and even doing a \\g<0> shows strange, irregular matches. 我想使用最后一个正则表达式,但是无论如何,捕获组都被弄乱了,甚至执行\\ g <0>都显示出奇怪的,不规则的匹配。 I would think that capture group 3 would be the last word boundary, but it doesn't appear to be.
我认为捕获组3将是最后一个词的边界,但似乎并非如此。
A sample sentence could be: I like candy.
例句可能是:
I like candy.
I am not interested very much in the correctness of the replacement (me will never actually be selected since I goes first), but I don't know why the capture groups don't work as I would expect. 我对替换的正确性不是很感兴趣(自从我第一次去以来我就永远不会被选中),但是我不知道为什么捕获组不能按我期望的那样工作。
Thanks! 谢谢!
Try with following regex. 尝试使用以下正则表达式。
Regex: \\b(I|me)\\b
正则表达式:
\\b(I|me)\\b
Explanation: 说明:
\\b
on both sides marks the word boundary. 两侧的
\\b
标记单词边界。
(I|me)
matches either I
OR me
. (I|me)
匹配I
或me
。
Note:- You can make it case insensitive using i
flag. 注意:-您可以使用
i
标志使其不区分大小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.