簡體   English   中英

Python,用於過濾元素的正則表達式以列表中的樣式結尾

[英]Python, regex to filter elements endswith a style in a list

使用正則表達式,我想找出列表中的哪些元素,以樣式(yyyy-mm-dd)結尾,例如(2016-05-04)等。

模式r'(2016- \\ d \\ d- \\ d \\ d)'看起來還算天真。 將它與Endswith結合的正確方法是什么?

謝謝。

import re

a_list = ["Peter arrived on (2016-05-04)", "Building 4 floor (2020)", "Fox movie (2016-04-04)", "David 2016-08-", "Mary comes late(true)"]

style = r'\(2016\-\d\d\-\d\d\)'

for a in a_list:
    if a.endswith(style):
        print a

您不能將正則表達式與字符串操作結合使用。 只需使用re.search查找匹配項,然后在模式中使用錨點$檢查匹配項是否在末尾發生

>>> import re
>>> style = re.compile(r'\(2016-\d\d-\d\d\)$')
>>> for a in a_list:
...     if style.search(a):
...         print (a)
... 
Peter arrived on (2016-05-04)
Fox movie (2016-04-04)

使用r'\\(\\d{4}-\\d{2}-\\d{2}\\)$'

例如:

import re

a_list = ["Peter arrived on (2016-05-04)", "Building 4 floor (2020)", "Fox movie (2016-04-04)", "David 2016-08-", "Mary comes late(true)"]

style = r'\(\d{4}-\d{2}-\d{2}\)$'

for a in a_list:
    if re.search(style, a):
        print a

輸出:

Peter arrived on (2016-05-04)
Fox movie (2016-04-04)

這將是

.*\(2016\-\d{2}\-\d{2}\)$

$符號在末尾表示

暫無
暫無

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

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