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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With