簡體   English   中英

檢查列表是否有一個或多個與正則表達式匹配的字符串

[英]Check if a list has one or more strings that match a regex

如果需要說

if <this list has a string in it that matches this rexeg>:
    do_stuff()

發現這個強大的構造從列表中提取匹配的字符串:

[m.group(1) for l in my_list for m in [my_regex.search(l)] if m]

......但這很難讀懂和矯枉過正。 我不想要列表,我只是想知道這樣的列表是否包含任何內容。

是否有更簡單的閱讀方式來獲得答案?

你可以簡單地使用any 演示:

>>> lst = ['hello', '123', 'SO']
>>> any(re.search('\d', s) for s in lst)
True
>>> any(re.search('\d{4}', s) for s in lst)
False

如果要從字符串的開頭強制執行匹配,請使用re.match

說明

any都會檢查迭代中是否存在任何真值。 在第一個例子中,我們傳遞以下列表的內容(以生成器的形式):

>>> [re.search('\d', s) for s in lst]
[None, <_sre.SRE_Match object at 0x7f15ef317d30>, None]

它有一個匹配對象,它是真實的,而None總是在布爾上下文中計算為False 這就是為什么any將為第二個示例返回False

>>> [re.search('\d{4}', s) for s in lst]
[None, None, None]

暫無
暫無

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

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