簡體   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