Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex match whole string only

Tags:

python

regex

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')
like image 565
Antimony Avatar asked Dec 20 '15 20:12

Antimony


People also ask

How do you match a whole string in Python?

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.

How do I match an exact pattern in Python?

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.

What will the '$' regular expression match?

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.


1 Answers

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'>
like image 168
Padraic Cunningham Avatar answered Sep 29 '22 15:09

Padraic Cunningham