Vin*_*shi 3 python regex python-2.7
我有一个包含&&
.
我想替换所有左右两侧&&
都有空格的内容。
示例字符串:
x&& &&& && && x
Run Code Online (Sandbox Code Playgroud)
期望的输出:
x&& &&& and and x
Run Code Online (Sandbox Code Playgroud)
我的代码:
import re
print re.sub(r'\B&&\B','and','x&& &&& && && x')
Run Code Online (Sandbox Code Playgroud)
我的输出
x&& and& and and x
Run Code Online (Sandbox Code Playgroud)
请建议我,如何防止&&&
被替换and&
。
您可以使用此环视正则表达式进行搜索:
(?<= )&&(?= )
Run Code Online (Sandbox Code Playgroud)
并替换为and
代码:
p = re.compile(ur'(?<= )&&(?= )', re.IGNORECASE)
test_str = u"x&& &&& && && x"
result = re.sub(p, "and", test_str)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1979 次 |
最近记录: |