我不太熟悉正则表达式,所以需要你帮忙解决下面这个看起来有些棘手的问题。
假设我有以下字符串:
string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
如何使用正则表达式获取title:hello
,title:world
,从原始字符串中删除这些字符串,并保留其中被双引号包围的"title:quoted"
?
我已经看到了这个类似的 SO 回答,以下是我得出的答案:
import re
string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
def replace(m):
if m.group(1) is None:
return m.group()
return m.group().replace(m.group(1), "")
regex = r'\"[^\"]title:[^\s]+\"|([^\"]*)'
cleaned_string = re.sub(regex, replace, string)
assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3'
当然,它不起作用,我并不感到惊讶,因为正则表达式对我来说很费解。
谢谢你的帮助!
最终解决方案
感谢你们的答案,这是最终的解决方案,适合我的需求:
import re
matches = []
def replace(m):
matches.append(m.group())
return ""
string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
regex = '(?<!")title:[^\s]+(?!")'
cleaned_string = re.sub(regex, replace, string)
# remove extra withespaces
cleaned_string = ' '.join(cleaned_string.split())
assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3'
assert matches[0] == "title:hello"
assert matches[1] == "title:world"
[关键词1,关键词2,标题:你好,标题:单词,关键词3]
? - PepperoniPizza[title:hello, title:world]
,并将它们从字符串中删除。 - Agate