在 python 中使用 re.sub 将“&&”替换为“and”。

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&

anu*_*ava 5

您可以使用此环视正则表达式进行搜索:

(?<= )&&(?= )
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)

正则表达式演示

  • 是的,当然。`(?&lt;= )` 是一个正向后查找,确保 `&amp;&amp;` 前面有一个空格。`(?= )` 是一个积极的前瞻,确保 `&amp;&amp;` 后面有一个空格。 (2认同)