替换所有匹配正则表达式的出现 [英] Replace all occurrences that match regular expression

查看:38
本文介绍了替换所有匹配正则表达式的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式,用于搜索包含 '.00.''.11.' 的字符串,如下所示:

I have a regular expression that searches for a string that contains '.00.' or '.11.' as follows:

.*\.(00|11)\..*

我想做的是用 'X00X''X11X' 替换所有与模式匹配的事件.例如,字符串 '.00..0..11.' 将导致 'X00X.0.X11X'.

What I would like to do is replace all occurrences that match the pattern with 'X00X' or 'X11X'. For example, the string '.00..0..11.' would result in 'X00X.0.X11X'.

我正在研究 Python re.sub 方法,但不确定如何有效地执行此操作.返回的匹配对象仅在第一次出现时匹配,因此效果不佳.有什么建议吗?我应该为此任务使用字符串替换吗?谢谢.

I was looking into the Python re.sub method and am unsure of how to do this effectively. The returned match object only matches on the first occurrence and therefore doesn't work well. Any advice? Should I just be using a string replace for this task? Thanks.

推荐答案

re.sub()(Python 2Python 3) 确实会替换它找到的所有匹配项,但是您使用 .* 可能会导致正则表达式匹配太多(即使是其他出现的 .00. 等).只需:

re.sub() (docs for Python 2 and Python 3) does replace all matches it finds, but your use of .* may have caused the regex to match too much (even other occurences of .00. etc.). Simply do:

In [2]: re.sub(r"\.(00|11)\.", r"X\1X", ".00..0..11.")
Out[2]: 'X00X.0.X11X'

注意模式不能重叠:

In [3]: re.sub(r"\.(00|11)\.", r"X\1X", ".00.11.")
Out[3]: 'X00X11.'

这篇关于替换所有匹配正则表达式的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆