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.

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

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

LINKS

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com