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'>
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'>
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 alsosearch()
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