Is there any easy way to test whether a regex matches an entire string in Python? I thought that putting $
at the end would do this, but it turns out that $
doesn't work in the case of trailing newlines.
For example, the following returns a match, even though that's not what I want.
re.match(r'\w+$', 'foo\n')
fullmatch() function in Python. re. fullmatch() returns a match object if and only if the entire string matches the pattern. Otherwise, it will return None.
To match an exact string using Python's regex library re , use the string as a regex. For example, you can call re.search('hello', 'hello world') to match the exact string 'hello' in the string 'hello world' and return a match object.
It's often useful to anchor the regular expression so that it matches from the start or end of the string: ^ matches the start of string. $ matches the end of the string.
You can use \Z
:
\Z
Matches only at the end of the string.
In [5]: re.match(r'\w+\Z', 'foo\n')
In [6]: re.match(r'\w+\Z', 'foo')
Out[6]: <_sre.SRE_Match object; span=(0, 3), match='foo'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With