Python practical techniques first 22: Using Shell wildcard string matching to do

1, demand

When working in UNIX Shell, we want to use common wildcard patterns (ie: .py, Dat [0-9] .csv, etc.) to do the matching text.

2. Solution

fnmatch module provides two functions: fnmatch () and fnmatchcase (), can be used to perform such matching, very simple to use.

Example:

from fnmatch import fnmatch,fnmatchcase
print(fnmatch('mark.txt','*.txt'))
print(fnmatch('mark.txt','?ark.txt'))
print(fnmatch('mark2018.txt','?ark201[0-9].txt'))
Python资源分享qun 784758214 ,内有安装包,PDF,学习视频,这里是Python学习者的聚集地,零基础,进阶,都欢迎

operation result:

True
True
True

In general, the fnmatch () matching the case of rules with the same underlying file, for example:

print(fnmatch('mark.txt','*.TXT'))

The above code, in the Max runs to False, run under Windows to True.

If this case distinctions is important to us, we should use fnmatchcase (). It will do exactly match based on the case method we offer.

Example:

from fnmatch import fnmatch,fnmatchcase
print(fnmatchcase('mark.txt','*.TXT'))

result:

False

On these functions, a feature often overlooked is their potential use in the treatment of non-filename-style string.

E.g,

from fnmatch import fnmatchcase

#假设有一组街道地址,就像这样:
address=[
    '111 A 上海 SH',
    '112 B 上海 SH',
    '113 C 上海 SH',
    '124 D 北京 BJ',
    '138 E 北京 BJ',
    '145 F 北京 BJ',
]

result=[addr for addr in address if fnmatchcase(addr,'1[1-3][1-5]*BJ')]
print(result)

operation result:

['124 D 北京 BJ']
Python资源分享qun 784758214 ,内有安装包,PDF,学习视频,这里是Python学习者的聚集地,零基础,进阶,都欢迎

3, analysis

fnmatch complete matching operation between a bit string of simple methods and full function between regular expressions.

If you actually want to write code that matches the file name, you should use the glob module to complete, will be introduced later to.

Guess you like

Origin blog.51cto.com/14445003/2429269