4
votes

I'm having trouble matching a digit in a string with Python. While it should be clearly matched, It doesn't even match [0-9] [\d] or just 0 alone. Where is my oversight?

import re

file_without_extension = "/test/folder/something/file_0"

if re.match("[\d]+$", file_without_extension):
   print "file matched!"
3
Which part are you trying to match exactly? Are you trying to get the bits between the slashes? or just the filename at the end? Or literally just the number at the end? - rcbevans
Are you trying to check if a number is there, i.e use search, or extract the number from it, i.e re.findall? - rcbevans
Incidentally: always use raw strings for regexps (r"[\d]+$"). Otherwise you'll be back here with another mysterious problem in a few days. - alexis

3 Answers

8
votes

Read the documentation: http://docs.python.org/2/library/re.html#re.match

If zero or more characters at the beginning of string

You want to use re.search (or re.findall)

4
votes

re.match is "anchored" to the beginning of the string. Use re.search.

0
votes

Use re.search instead of re.match.