0

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?

JustAC0der
  • 2,871
  • 3
  • 32
  • 35

2 Answers2

1

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())
.
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

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

user3030010
  • 1,767
  • 14
  • 19