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?
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?
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())
.
match
looks for matches at the beginning of the string, unless you tell it to do otherwise. The dot isn't at the beginning of the string, so it can't be found.
See the documentation here: https://docs.python.org/3/library/re.html#re.match