繁体   English   中英

如何在正则表达式上为 re.findall 和 re.finditer 得出相同的结果?

[英]How can I make same result for re.findall and re.finditer on regular expressions?

话题

我想使用re.finditer() function 而不是 re.findall() 来提取带引号的单词或引号。

text = 'This is a very "sweet" and "beautiful" cake.'

-> ['sweet', 'beautiful']

output 一个问题

re.finditer() function 返回带引号,我不知道如何摆脱顶部和底部的双引号。

['sweet', 'beautiful']
['"sweet"', '"beautiful"']

代码

import re
text = 'This is a very "sweet" and "beautiful" cake.'
all = re.findall('"(.*?)"', text)
print(all)

all_obj = re.finditer('"(.*?)"', text)
result = []
for obj in all_obj:
    result.append(obj.group())
print(result)

我试图做的

如果不剥离,是否有任何解决方案可以解决此问题?

final_result = []
for word in result:
    final_result.append(word.rstrip('"').lstrip('"'))
print(final_result)

['sweet', 'beautiful']

请使用.group(1)匹配并提取您的组:

result.append(obj.group(1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM