JustAC0der JustAC0der - 13 days ago 6
Python Question

Python regex should match a dot but it does not

I have the following Python 3 code:

import re
pattern=re.compile(r'\.')
print(pattern.match('abc.de'))


The output is:

None


What am I doing wrong? Why the regex does not match the dot?

Answer

As per the documentation of match it checks from the beginning of a string.

If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.


Use search instead for search at any position.

>>> import re
>>> pattern=re.compile(r'\.')
>>> print(pattern.search('abc.de'))
<_sre.SRE_Match object at 0x7fc7b5823648>
>>> print(pattern.search('abc.de').group())
.