"Python Cookbook" "String and Text" 3. String matching using shell wildcard characters

Source: Internet
Author: User
Tags uppercase letter

Issue: Use common wildcard patterns (i.e., *.py, dat[0-9]*.csv, etc.) to match text when working under a Linux shell

Solution: The Fnmatch module provides two functions Fnmatch (), Fnmatchcase ()

The match pattern for #fnmatch () uses the same case-sensitive rules as the underlying file system (different depending on the operating system)

Match patterns for #fnmatchcase () are case-sensitive

>>> fromFnmatchImportFnmatch,fnmatchcase>>> Fnmatch ('foo.txt','. txt') False>>> Fnmatch ('foo.txt','*.txt') True>>> Fnmatch ('foo.txt','? oo.txt') True>>> Fnmatch ('Dat34.csv','dat[0-9]*') True>>> names=['Dat34.csv','Dat1.csv','Config.ini','foo.py']>>> [Name forNameinchNamesifFnmatch (Name,'Dat*.csv')]['Dat34.csv','Dat1.csv']>>>
>>> fnmatch ('foo.txt','*. TXT')#onWINDOWS uppercase match True>>> fnmatchcase (' foo.txt ', ' *. TXT ') #on Windows uppercase letter Matching
False
>>> >>> fnmatch ('foo.txt','*. TXT')#onOS X (MAC) uppercase match False

One potential use of these functions is when they handle non-file-name strings.

#example.py##Example of using Shell-wildcard style matching in list comprehensions fromFnmatchImportFnmatchcase as Matchaddresses= [    '5412 N CLARK ST',    '1060 W ADDISON ST',    '1039 W GRANVILLE AVE',    '2122 N CLARK ST',    '4802 N BROADWAY',]a= [addr forAddrinchAddressesifMatch (addr,'* ST')]Print(a) b= [addr forAddrinchAddressesifMatch (addr,'54[0-9][0-9] *clark*')]Print(b)
>>> ================================ RESTART ================================>>> ['  5412 N Clark St'1060 W ADDISON St'2122 N Clark St ' ['5412 N CLARK ST']

In fact, you want to write code that matches the file name, which should be done using the Glob module.

"Python Cookbook" "String and Text" 3. String matching using shell wildcard characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.