用另一个角色Python正则替换第一和第三个出现



我今天正在处理正则是

的图案

所以我想要的是

gere  should be gara 
cateral    should remain cateral  

为此,我使用RE模块使用了以下等级。

stg = "my string is here "
re.sub(r'e?e','a',stg)

上述表达式的问题是它与gere合作正常工作,并将结果与gara

给予。

,但cateral也随cataral

更改

我只想在E(任何单个字符(E替换为(任何单个字符(a

的地方

请让我知道我在这里做错了什么。

谢谢

我同意 @wiktor-stribiêew的答案,但做了一个工作示例。我还从此Google教程页面的底部记下了一张笔记。

基本上,我们要替换可能在中间字母的非连续的" e"值(对我来说,空间会指示一个单独的单词,并且与模式不匹配(。

我试图弄清楚如何进行分组,并从类似'(e( w ?(e('之类的东西开始,但发现相反的情况是正确的。我们想"捕获"并保留两个E之间的任何东西,同时用A代替E。

无论如何,这是我的解决方案:

import re
sstr = """
gere  should be gara 
cateral    should remain cateral 
"""
### Our pattern captures and preserves whatever is in between the e's
### Note that w+? is non-greedy and looks for at least one word character between the e's.
regex = r'e(w+?)e'
### We then sub out the e's and replace the middle with out capture group, which is group(1).
### Like w, the backslash escapes the 1 for group-referencing purposes.
### If you had two groups, you could retain the second one with 2, and so on.
new_str = re.sub(regex, r'a1a', sstr)
### Output answer to the terminal.
print(new_str)

输出:

gara  should be gara 
cateral    should remain cateral 

e?e Regex匹配可选的e,然后匹配e,因此您的re.sub(r'e?e','a',stg)命令用a替换eee的每种出现。例如。geese将变成gase,将get变成gat

您可以使用以下一个:

re.sub(r'e(.)e', r'a1a', stg)         # . - any char but line break char
re.sub(r'e([a-z])e', r'a1a', stg)     # [a-z] - any lowercase ASCII letter
re.sub(r'e([^Wd_])e', r'a1a', stg)  # [^Wd_] - any Unicode letter

请参阅在线python演示。

正则详细信息:

  • e-匹配e
  • (.)-捕获除线片以外的任何其他字符
  • e- e
  • 替换模式中的1插入了与第1组内存缓冲区中存储的相同值。

请参阅Regex Demo在线。

最新更新