0

It appears that python regex is not matching when the target string has a dot. Is this a feature? Am I missing something? Thanks!

>>> import re
>>> re.compile('txt').match('txt')
<_sre.SRE_Match object at 0x7f2c424cd648>
>>> re.compile('txt').match('.txt')
>>>
exp2logy
  • 35
  • 4

1 Answers1

0

The docs are quite explicit about the difference between search and match:

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

You should therefore replace match with search:

In [9]: re.compile('txt').search('.txt')
Out[9]: <_sre.SRE_Match at 0x7f888afc9cc8>

I don't know the history behind this quirk (which, let's face it, must trip a lot of people up), but I'd be interested to see (in the comments) why re offers a specific function for matching at the start of a string.

In general, I'm broadly against anything whose name is broad enough that you have to go to the docs to work out what it does.

LondonRob
  • 73,083
  • 37
  • 144
  • 201