4

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!"
4
  • 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? Commented May 15, 2013 at 15:26
  • Are you trying to check if a number is there, i.e use search, or extract the number from it, i.e re.findall? Commented May 15, 2013 at 15:30
  • 1
    Incidentally: always use raw strings for regexps (r"[\d]+$"). Otherwise you'll be back here with another mysterious problem in a few days. Commented May 15, 2013 at 18:06
  • How a bad naming could cost us time? Why not a direct "startWith"? Commented Apr 24, 2024 at 22:17

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was only making sure the regex was right neglecting if I was even using the right function.
6

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

Comments

1

Use re.search instead of re.match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.