-1

Why does Python's regex module not recognize "[1]" in this following code?

In [43]: re.match (r"1",  "[1]")

In [44]:

whereas this works:

In [46]: re.match (r"1",  "123")
Out[46]: <re.Match object; span=(0, 1), match='1'>
zell
  • 9,830
  • 10
  • 62
  • 115
  • 1
    From python.org: `match() Determine if the RE matches at the beginning of the string.` https://docs.python.org/3/howto/regex.html#performing-matches – Cow May 19 '22 at 12:29
  • 1
    This is expected behavior, `re.match` does only look for pattern at beginning, if you wish to match anywhere in string use `re.search` – Daweo May 19 '22 at 12:29
  • Does this answer your question? [Python regular expression re.match, why this code does not work?](https://stackoverflow.com/questions/14933771/python-regular-expression-re-match-why-this-code-does-not-work) – mkrieger1 May 19 '22 at 12:30

1 Answers1

1

From docs.python.org:

re.match(pattern, string, flags=0)

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

...

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Since your 'string' starts with an [, it's not captured.

As suggested by the docs, using re.search(r"1", "[1]") does match it since it will match anywhere in the string


whereas this works:

In [46]: re.match (r"1",  "123")`
Out[46]: <re.Match object; span=(0, 1), match='1'>

Here the 'string' starts with the pattern and is being matched as expected

0stone0
  • 34,288
  • 4
  • 39
  • 64