8

In Python I can do

import re
re.match("m", "mark")

and I get the expected result:

<_sre.SRE_Match object; span=(0, 1), match='m'>

But it only works if the pattern is at the start of the string:

re.match("m", "amark")

gives None. There is noting about that pattern which requires it to be at the start of the string - no ^ or similar. Indeed it works as expected on regex101.

Does Python have some special behaviour - and how do I disable it please?

Community
  • 1
  • 1
Mark Smith
  • 880
  • 1
  • 8
  • 25
  • 2
    This question is not a duplicate of the one marked. Yes the answers are duplicates, but the question comes at the problem from a completely different angle. I would have to have known the answer to my question to recognise the other as a "duplicate". – Mark Smith Dec 09 '15 at 10:39
  • It is a dupe by all means, if not that one, there is another one regarding `re.match`. BTW, `re.match` is not matching at the start of a *line*, it only matches at the start of a *string*. – Wiktor Stribiżew Dec 09 '15 at 10:44
  • I didn't say it wasn't a dupe. I said it wasn't a dupe of the one marked. It should be marked as a dupe of a question it's a dupe of, not of some other one. – Mark Smith Dec 09 '15 at 11:08
  • 1
    It's definitely a duplicate. Besides, the documentation for `re.match` clearly says that it tries to "apply the pattern at the start of the string." A few moments of research would have been well-spent here. – TigerhawkT3 Dec 09 '15 at 11:09
  • 1
    I'd like to note that the question phrased in this fashion made it possible for me to find an answer. I did read the docs, but I missed that on my first pass. Thank you for asking this question. – David Culbreth Sep 02 '18 at 16:12
  • @DavidCulbreth You and (at least) 10 other people, apparently, judging by the number of up-votes on the answer to date. – Mark Smith Sep 02 '18 at 16:27

2 Answers2

16

From the docs on re.match:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object.

Use re.search to search the entire string.

The docs even grant this issue its own chapter, outlining the differences between the two: search() vs. match()

hlt
  • 6,219
  • 3
  • 23
  • 43
0
import re 
re.match("[^m]*m", "mark")

match matches from beginning of string.So you need to give it a way to match the start of string if m is not at start of string.

vks
  • 67,027
  • 10
  • 91
  • 124