abc abc - 2 months ago 18
Python Question

Python compiled pattern match with flags, cp.search to match at beginning of line

I have this, which gives no match, why ?:

>>> p = r'abc'
>>> cp = re.compile(p, re.IGNORECASE)
>>> m = cp.search('ABC', re.IGNORECASE)
>>> m # NO MATCH # 1


But, this gives a match, why ?

>>> m = cp.search(' ABC', re.IGNORECASE) # introduced spaces, ABC no longer at the beginning
>>> m # MATCH # 2
<_sre.SRE_Match object at 0x1082b5ac0>


To get a match in #1 all I have to do is drop re.IGNORECASE, why so ?

>>> m = cp.search('ABC')
>>> m
<_sre.SRE_Match object at 0x10827e308>

Answer Source

If (in the interpreter) you print out the help on cp.search:

help(cp.search)

you will see:

Help on built-in function search:
search(string=None, pos=0, endpos=9223372036854775807, *, pattern=None) method of _sre.SRE_Pattern instance
    Scan through string looking for a match, and return a corresponding match object instance.

    Return None if no position in the string matches.

Notice that this function does not take any flags, but what you were actually passing your flag to the 'pos' argument, which was why you got an unexpected result.