簡體   English   中英

python regex:匹配第一個“}”

[英]python regex: match to the first “}”

我有一個字符串s包含:

Hello {full_name} this is my special address named {address1}_{address2}.

我試圖匹配花括號中包含的所有字符串實例。

嘗試:-

matches = re.findall(r'{.*}', s)

給我

['{full_name}', '{address1}_{address2}']

但是我實際上試圖檢索的是

['{full_name}', '{address1}', '{address2}']

我怎樣才能做到這一點?

>>> import re
>>> text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
>>> re.findall(r'{[^{}]*}', text)
['{full_name}', '{address1}', '{address2}']

嘗試非貪婪的比賽:

matches = re.findall(r'{.*?}', s)

您需要一個非貪婪的量詞:

matches = re.findall(r'{.*?}', s)

注意問號?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM