Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string is equal to regex in Python?

Tags:

python

regex

Is there any way to check if a string is exactly equal to a regular expression in Python? For example, if the regex is \d\s\d, it should allow strings 1 5, 8 2, etc, but not lorem 9 4 ipsum or a7 3.

like image 310
tkbx Avatar asked Jan 16 '23 22:01

tkbx


1 Answers

Strings and regex are different types. I think you're looking to check not whether a string is "exactly equal to" a regex, but that the regex matches the entire string. To do that, just use start and end anchors (^ and $, respectively) in the regex. For example:

^\d\s\d$

instead of

\d\s\d
like image 143
Matt Ball Avatar answered Jan 22 '23 08:01

Matt Ball