Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Python does not mach string (but it does when checking on rubular)

Tags:

python

regex

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!

like image 529
Guio Avatar asked Aug 05 '26 14:08

Guio


1 Answers

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.

like image 196
acattle Avatar answered Aug 07 '26 05:08

acattle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!