我有一个输入,需要将 &&
替换为 and
注意: && 作为左右空格,输出也应包含左右空格 和
输入:
s = 'n && && && && && &&n'
我的代码:
m=re.sub(r'\s[&&]\s', ' and ',s)
print(m)
我的输出:
n && && && && && &&n
预期输出:
n and and and and and &&n
最佳答案
我会在 (?<!\S)&&(?!\S)
上进行正则表达式替换:
import re
s = 'n && && && && && &&n'
output = re.sub(r'(?<!\S)&&(?!\S)', 'and', s)
print(output) # n and and and and and &&n
这里的正则表达式模式表示匹配:
-
(?<!\S)
断言前面是空格或输入的开头 -
&&
匹配文字&&
-
(?!\S)
断言后面的内容是空格或输入的结尾
关于python-3.x - 需要找到完全匹配并使用正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76294931/