I seem not to get it right in regex in python when matching digits

Viewed 122

I have a list containing items that mirror file names. I would like to filter only the names that are contain only digits. I seem not to get it right. Even matching a a single digit seem not to be working. Am I the one not doing it right? Any leads or suggestions would be appreciated.

Sample of code:

import re

pattern = r"^\d.+[.]"
pattern2 = r'\d*'

a = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for i in a:
    if re.match(i, pattern):
        print(i)
3 Answers

This is a working code. You can fiddle around the regex to get a better regex string for matching without dot character.

import re

pattern = re.compile(r"^[0-9]+.")

a = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for i in a:
    match = re.match(pattern, i)
    if match:
        matched_string = match.group(0)
        string_without_dot = matched_string[0:len(matched_string)-1]
        print(string_without_dot)

This should work:

pattern = r"\d+?.\w+"

Or, if you want to capture the file name:

pattern = r"(\d+?).\w+"

But this will not work if your filename contains ".".

It appears that you have mistaken the argument order of the re.match function.

Here is a code that I have tested and does what you require:

# Regex explanation,
# ^ Indicates position at start of a line.
# \d+ Indicates any digit and can be N number of times. Digit is defined as [0-9].
# \. Indicates a literal .
# \w+ Indicates any word and can be N number of times. Word is defined as [a-zA-Z0-9_].
pattern = r'^\d+\.\w+'

files_list = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for file in files_list:
    # The order of arguments for re.match should be, (pattern, string).
    if re.match(pattern, file):
        print(file)

Output:

1000.mp4
110082.mp4
829873.m4a
Related