Python正则表达式返回分组中不带双引号的单词



我正在尝试使用regex分组将字符串的值存储到字典中。其中一个组必须返回双引号内的文本(不带引号(。我曾经尝试过使用查找法来获取引号中的文本,但在一组其他内容中不起作用。期望的结果是{'first_word': 'Remove', 'check': 'this'}

sampledata= 'Remove "this"'
pattern="""
(?P<first_word>w*)                #This group is to capture the preceeding word      
(s)                               #This is a dummy group to capture space
(?P<check>(?<=")w*(?="))        #This group is to find the word between quotes and return only the word
"""
for item in re.finditer(pattern,sampledata,re.VERBOSE):
print(item.groupdict())

以下代码根据需要对数据进行分组,但返回带引号的文本,因此无法使用。

sampledata= 'Remove "this"'
pattern="""
(?P<first_word>w*)                #This group is to capture the preceeding word      
(s)                               #This is a dummy group to capture space
(?P<check>["](.*?)["])             #This group is to find the word between quotes and return only the word
"""
for item in re.finditer(pattern,sampledata,re.VERBOSE):
print(item.groupdict())

我在这里错过了什么?

只需将双引号移到第二组之外,就可以了:

sampledata = 'Remove "this"'
pattern = r'(?P<first_word>w*)s"(?P<check>w*)"'
for item in re.finditer(pattern, sampledata, re.VERBOSE):
print(item.groupdict())  # {'check': 'this', 'first_word': 'Remove'}

你是说如何获得一个内双引号字符串吗?如果是

输入:'hello "world"'
正则表达式:"(.+)"

匹配1:"world"
组1:world

最新更新