3

As part of a bigger code I am trying to check if a string(filename) ends with ".number" However, re.match (re.compile and match) just wont match the pattern at end of the string.

Code:

import re
f = ".1.txt.2"
print re.match('\.\d$',f)

Output:

>>> print re.match('\.\d$',f)
None

Any help will be much appreciated !

Amar
  • 69
  • 1
  • 9
  • Possible duplicate of [Python regular expression re.match, why this code does not work?](http://stackoverflow.com/questions/14933771/python-regular-expression-re-match-why-this-code-does-not-work) – rock321987 Dec 11 '16 at 07:43

2 Answers2

5

Use search instead of match


From https://docs.python.org/2/library/re.html#search-vs-match

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.

ColBeseder
  • 3,579
  • 3
  • 28
  • 45
  • Wow - yep. Surprising. I think `re.match('^.*(\.\d)$',f).group(1)` would also work. – alex Jan 23 '20 at 20:17
0

You can try this

import re
word_list = ["c1234", "c12" ,"c"]
for word in word_list:
    m = re.search(r'.*\d+',word)
    if m is not None:
        print(m.group(),"-match")
    else:
        print(word[-1], "- nomatch")
PemaGrg
  • 722
  • 7
  • 5