當字串中重復多次時,是否可以提取包含在特定字符集 {} 中的文本?
string = 'Revenue for the period is {value="32", font="34"} and EBITDA is {value="12", font="34"} for 2022'
輸出應包含實體作為字串格式的串列中的元素。
output = ['{value="32", font=34}', '{value="12", font=34}']
uj5u.com熱心網友回復:
您可以使用re正則運算式模式來匹配大括號中的文本:
import re
# Dont use str (a built-in class) as a variable name
string = 'Revenue for the period is {value="32", font="34"} and EBITDA is {value="12", font="34"} for 2022'
output = re.findall(r'{[^}] }', string)
>>> output
['{value="32", font="34"}', '{value="12", font="34"}']
請注意,如果沒有匹配項,則為output空list
在線演示:https ://regex101.com/r/XB7U9g/1
我對學習正則運算式模式的建議:https ://regexone.com/
uj5u.com熱心網友回復:
您可以使用函式re.findall():
import re
text = (
'Revenue for the period is {value="32", font="34"} and EBITDA is {value="12", '
'font="34"} for 2022'
)
pattern = re.compile(r'{value="\d ", font="\d "}')
print(re.findall(pattern, text))
輸出:
['{value="32", font="34"}', '{value="12", font="34"}']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/490260.html
標籤:Python python-3.x 细绳 列表
