【发布时间】:2021-04-13 07:12:03
【问题描述】:
我想读入一个字符串并删除捕获的组(在本例中为“[^ ]+(&)[^ ])。
x = "apple&bob & john & smith" # original string
x = "applebob & john & smith" #after replacing string
这是我现在使用的代码。
import re
and_regex = re.compile(r'([^ ]+(&)[^ ])')
x = "apple&bob & john & smith"
x = re.sub(and_regex, " ",x)
print(x)
我不能使用字符串替换(string.replace),因为它会替换整个字符串中的“&”。
感谢您的帮助!
【问题讨论】:
-
我想知道环顾四周是否会有所帮助:
re.compile(r'(?<=\S)&(?=\S)'). -
&apple&bob & john & smith&的预期是什么?
标签: python python-3.x regex string