In this article, we will learn about VERBOSE flag of the re package and how to use it.
re.VERBOSE : This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments.
Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like
*?, (?: or (?P. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.
It’s passed as an argument to
re.compile() i.e re.compile(Regular Expression, re.VERBOSE).
re.compile() returns a RegexObject which is then matched with the given string.
Let’s consider an example where the user is asked to enter their Email ID and we have to validate it using RegEx. The format of an email is as follow:
- Personal details/local part like john123
- Single @
- Domain Name like gmail/yahoo etc
- Single Dot(.)
- Top Level Domain like .com/.org/.net
Input : email@example.com Output : Valid Input : firstname.lastname@example.org@ Output : Invalid This is invalid because there is @ after the top level domain name.
Below is the Python implementation –
email@example.com is Valid. Details are as follow: Local:expectopatronum Domain:gmail Top Level domain:com firstname.lastname@example.org@ is Invalid Crucio@.com is Invalid
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.