How to Validate Input with Regex in Python

The aim of this page📝 is to remember how to simply add an input validation and raise ValueError in Python in case it does not conform to my needs.

Pavol Kutaj
2 min readNov 3, 2022

My script needs to take a client tag in the form of

com_acme

The underscore is essential and it cannot be the . as in com.acme

Sure, I can make the script more robust by doing the replacement in case the input arrives with . instead of _ but I want something more strict and explicit as this is a dialog process and colleagues should be informed about proper syntax for reasons irrelevant here.

Just memorize ‘if not re.match(<regex>, <input> ): raise ValueError(<error_message>)’

Match objects always have a boolean value of True. Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement

import re
def validate_client_input(client: str) -> None:
if not re.match("^\w{1,}_\w{1,}$", client):
raise ValueError(
"Client name has to have the form of com_acme (note the underscore separator)")

LINKS

--

--

No responses yet