如何在 Python 3 中使用正则表达式搜索和替换文本中的模式? [英] How do I search and replace a pattern in text using regular expression in Python 3?
本文介绍了如何在 Python 3 中使用正则表达式搜索和替换文本中的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 3 中使用正则表达式搜索和替换文本中的模式?
How do I search and replace a pattern in text using regular expression in Python 3 ?
import re
text = "|105_Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"
result = re.sub("105_*", "105_Newtext1.6", text)
print(result)
我得到的结果是:
"|105_Newtext1.6Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"
我想用 105_Newtext1.6 替换 105_(任何文本)
I want to replace 105_(whatever text) by 105_Newtext1.6
推荐答案
*
不是这里的通配符 ;) 你可能需要这个:
The *
isn't a wildcard here ;) You might need this instead:
import re
text = "|105_Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"
result = re.sub("105_[^|]*", "105_Newtext1.6", text)
print(result)
*
表示前一个字符重复 0 次或多次.所以,[^|]*
意味着任何不是管道字符的字符被重复 0 次或更多次.
*
means that the previous character is repeated 0 or more times. So, [^|]*
means any character which is not a pipe character being repeated 0 or more times.
这篇关于如何在 Python 3 中使用正则表达式搜索和替换文本中的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文