Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expression match with file extension

Tags:

python

regex

I want to use Python regular expression utility to find the files which has this pattern:

000014_L_20111026T194932_1.txt
000014_L_20111026T194937_2.txt
...
000014_L_20111026T194928_12.txt

So the files I want have an underscore '_' followed by a number (1 or more digits) and then followed by '.txt' as the extension. I used the following regular expression but it didn't match the above names:

match = re.match('_(\d+)\.txt$', file)

What should be the correct regex to match the file names?

like image 824
tonga Avatar asked Dec 05 '25 00:12

tonga


1 Answers

You need to use .search() instead; .match() anchors to the start of the string. Your pattern is otherwise fine:

>>> re.search('_(\d+)\.txt$', '000014_L_20111026T194928_12.txt')
<_sre.SRE_Match object at 0x10e8b40a8>
>>> re.search('_(\d+)\.txt$', '000014_L_20111026T194928_12.txt').group(1)
'12'
like image 163
Martijn Pieters Avatar answered Dec 06 '25 17:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!