![](/img/trans.png)
[英]How can I replace two different sub strings in a string by using re.sub() in python?
[英]How can I replace text inside the parentheses using re.sub()
例如,我有一个像这样的字符串:
'(1) item 1. \n(2) item 2'
我应该这样结束:
'(x) item 1. \n(x) item 2'
我如何只将括号内的文本匹配,然后替换呢? 谢谢!
只是逃脱括号:
In [1]: import re
In [2]: s = '(1) item 1. \n(2) item 2'
In [3]: re.sub(r'\(\d+\)', '(x)', s)
Out[3]: '(x) item 1. \n(x) item 2'
您需要对它们进行转义,因为它们在正则表达式上下文中具有特殊含义(创建编号组)。
In [3]: import re
In [4]: re.sub("\([^)]*","(x",'(1) item 1. \n(2) item 2')
Out[4]: '(x) item 1. \n(x) item 2'
"\([^)]+\)"
将匹配括号中的任何内容,因此您可以
"(1) item 1. \n(2) item 2".gsub(/\([^)]+\)/, "(x)")
在红宝石中。
编辑:修复格式,以便转义不会丢失...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.