3

I'm writing a program in Python that uses regular expressions. I am having trouble because an expression that I think should match a string doesn't do it. This is the python code that reproduces my problem:

regex = re.compile(r"ord(er)? *0?([1-4])", re.I)
m = regex.match("CMord01")

m evaluates to FALSE. I would very much like to find out why. I've checked on http://rubular.com/ and there the expression does match the string as expected. Thank you!

3
  • 6
    Use regex.search() instead of regex.match(). See search() vs. match() in the Python docs. Commented May 28, 2013 at 15:30
  • Here in you expresion, the start of the string should be ord. It doesn't include CM. You probably want to prepend .* to your regexp. Commented May 28, 2013 at 15:30
  • @MarekKowalski that would obviously work but then all those junk characters are returned as part of the match. Depending on what they plan to do with the match, this might make things dirty/complicated Commented May 28, 2013 at 15:47

1 Answer 1

8

In Python re.match() matches from the beginning of the string. The first letter in CMord01 is C, not O, thus it does not match.

Most language's regular expression modules don't have this limitation so they match the string no problem. To have this kind of behaviour in Python you need to use re.search() instead. See "search() vs. match()" for more information on the difference between the two functions.

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

2 Comments

Cheers, problem solved! Wasn't aware of search() vs match(), now I know.
@Guio It's an idiosyncrasy of Python. I remember I had to exact same problem.

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.