简体   繁体   English

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

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

Topic话题

I would like to extract words or quotes with quotations without quotations using re.finditer() function rather than re.findall().我想使用re.finditer() function 而不是 re.findall() 来提取带引号的单词或引号。

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

-> ['sweet', 'beautiful']

output an issue output 一个问题

The re.finditer() function returns with quotations and I have no idea how to get rid of the top and bottom double quotations. re.finditer() function 返回带引号,我不知道如何摆脱顶部和底部的双引号。

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

Code代码

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)

What I have tried to do我试图做的

Without stripping, is there any solution to fix this issue?如果不剥离,是否有任何解决方案可以解决此问题?

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

['sweet', 'beautiful']

Please use .group(1) to match and extract your group:请使用.group(1)匹配并提取您的组:

result.append(obj.group(1))

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

相关问题 re.finditer 和 re.findall 之间的不同行为 - Different behavior between re.finditer and re.findall 正则表达式re.findall() - Regular Expressions re.findall() re.findall和re.finditer的区别-Python 2.7 re模块中的错误? - Differences in re.findall and re.finditer — bug in Python 2.7 re module? 为什么 re.findall() 给我的结果与 Python 中的 re.finditer() 不同? - Why does re.findall() give me different results than re.finditer() in Python? 除了在 python 中的 re.findall() 和 re.finditer() 中返回字符串和迭代器之外,它们的工作方式是否也不同? - Apart from returning string and iterator in re.findall() and re.finditer() in python do their working also differ? 在正则表达式中使用组时 re.findall() 和 re.finditer() 之间的区别? - Difference between re.findall() and re.finditer() when using groups in regex? 是否有Perl相当于Python的re.findall / re.finditer(迭代正则表达式结果)? - Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? 如何合并所有3合1 re.findall()(Python 2.7 &&正则表达式) - How to combine all 3 in 1 re.findall() ??(python 2.7 && Regular Expressions) Python 正则表达式 re.finditer 2 匹配 - Python Regular Expression re.finditer 2 matches Python正则表达式-re.search()与re.findall() - Python regular expressions - re.search() vs re.findall()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM