abc abc - 1 year ago 63
Python Question

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

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

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

But, this gives a match, why ?

>>> m =' 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 ='ABC')
>>> m
<_sre.SRE_Match object at 0x10827e308>

Answer Source

If (in the interpreter) you print out the help on


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download