4

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 1

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

Also worth noting that re.match() only looks at the start of the string, whereas re.search() searches the whole string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.