1. 程式人生 > >python-進階教程-利用萬用字元進行字串匹配

python-進階教程-利用萬用字元進行字串匹配

0.摘要

在Linux Shell中,我們可以用ls *.py的命令顯示所有以.py結尾的檔案或資料夾。在python中我們可以藉助fnmatch模組,實現含萬用字元的字串匹配。

 

1.常用萬用字元

符號 作用
* 匹配任何字串/文字,包括空字串;*代表任意字元(0個或多個) ls file *
? 匹配任何一個字元(不在括號內時)?代表任意1個字元 ls file 0
[abcd] 匹配abcd中任何一個字元
[a-z] 表示範圍a到z,表示範圍的意思 []匹配中括號中任意一個字元 ls file 0
{..} 表示生成序列. 以逗號分隔,且不能有空格
補充  
[!abcd] 或[^abcd]表示非,表示不匹配括號裡面的任何一個字元

 

2.fnmatch模組

from fnmatch import fnmatch, fnmatchcase

print(fnmatch('foo.txt', '*.txt'))   #True
print(fnmatch('foo.txt', '?oo.txt')) #True
from fnmatch import fnmatchcase as match

addresses = [
    '5412 N CLARK ST',
    '1060 W ADDISON ST',
    '1039 W GRANVILLE AVE',
    '2122 N CLARK ST',
    '4802 N BROADWAY',
]

a = [addr for addr in addresses if match(addr, '* ST')]
print(a)
# ['5412 N CLARK ST', '1060 W ADDISON ST', '2122 N CLARK ST']

b = [addr for addr in addresses if match(addr, '54[0-9][0-9] *CLARK*')]
print(b)
#['5412 N CLARK ST']