簡體   English   中英

使用正則表達式在同一行上查找多個匹配項

[英]Using regex to find multiple matches on the same line

我需要構建一個程序,該程序可以讀取多行代碼,並從每一行中提取正確的信息。 示例文字:

no matches
one match <'found'>
<'one'> match <found>
<'three'><'matches'><'found'>

在這種情況下,程序應將<'found'><'one'><'three'><'matches'><'found'>為匹配項,因為它們都具有“ <”和“ ' ” 。 但是,我無法計算出使用正則表達式來說明同一行上的多個匹配項的系統。 我正在使用類似的東西:

re.search('^<.*>$')

但是,如果一行上有多個匹配項,則多余的“ '< ”和“ >' ”將作為.*一部分,而不將它們視為單獨的匹配項。 我該如何解決?

這有效-

>>> r = re.compile(r"\<\'.*?\'\>")
>>> r.findall(s)
["<'found'>", "<'one'>", "<'three'>", "<'matches'>", "<'found'>"]

您可以使用re.findall並匹配尖括號內的非>字符:

>>> re.findall('<[^>]*>', "<'three'><'matches'><'found'>")
["<'three'>", "<'matches'>", "<'found'>"]

非貪婪量詞'?' 如anubhava建議的那樣,也是一種選擇。

使用findall而不是search

re.findall( r"<'.*?'>", str )

暫無
暫無

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

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