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.
1 Answer
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
1 Comment
Lenna
Also worth noting that
re.match() only looks at the start of the string, whereas re.search() searches the whole string.