简体   繁体   中英

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().

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

-> ['sweet', 'beautiful']

output an issue

The re.finditer() function returns with quotations and I have no idea how to get rid of the top and bottom double quotations.

['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:

result.append(obj.group(1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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