简体   繁体   中英

fnmatch - Matching for Patterns using quantifiers and other regex options

Hope you are all doing well.

I am currently using fnmatch to match for file names against patterns.

I have not had any issues with simple patterns involving *,?,[seq] as mentioned in the fnmatch documentation.

However I am not able to figure out a way to include other options such as +([0-9]).txt or [0-9]{6}.txt

I will maybe explain what I am trying to achieve. Assume we have 4 files in our source path.

123456.txt (No. of digits will vary)
123_test.txt
test_123.txt
123_test_456.txt

What pattern should be given in fnmatch that matches the file 123456.txt alone while ignoring the other patterns.

Env: Python 3.8

Thanks for all the help in advance.

You have to escape the dot to match it literally, and looking at the example data, you can use word boundaries:

\b\d+\.txt\b

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM