用另一个字符python regex替换第一次和第三次出现

2024-04-24 08:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天正在处理regex,想替换一个模式,如下所示

所以我想要的是

gere  should be gara 

cateral    should remain cateral  

为了做到这一点,我使用以下regex使用re模块。你知道吗

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

上述表达式的问题是,它与gere一起正常工作,并将结果提供给gara

但是cateral也随cataral而变化

我只想把e(任何单个字符)e替换成a(任何单个字符)a

请告诉我我做错了什么。你知道吗

谢谢


Tags: 模块restringismy模式be字符
2条回答

我同意@wiktor stribiżew的回答,但做了一个有效的例子。我还在谷歌教程页面的底部做了笔记。你知道吗

基本上,我们希望替换中间可能有一个字母的不连续的“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'a\1a', sstr)

### Output answer to the terminal.
print(new_str)

输出:

gara  should be gara 

cateral    should remain cateral 

e?e正则表达式匹配一个可选的e,然后匹配一个e,因此re.sub(r'e?e','a',stg)命令用a替换eee。例如geese会变成gaseget会变成gat。你知道吗

您可以使用以下选项之一:

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

参见Python demo online。你知道吗

正则表达式详细信息:

  • e-匹配e
  • (.)-将除换行符以外的任何字符捕获到组1中
  • e-一个e
  • \1在替换模式中插入与组1内存缓冲区中存储的值相同的值。你知道吗

参见regex demo online。你知道吗

相关问题 更多 >