Name validation using IGNORECASE in Python Regex
Last Updated :
29 Dec, 2020
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE.
re.IGNORECASE
: This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z]
will match lowercase letters, too. Generally, It’s passed as an optional argument to re.compile()
.
Let’s consider an example of a form where the user is asked to enter their name and we have to validate it using RegEx. The format for entering name is as follow:
- Mr. or Mrs. or Ms. (Either one) followed by a single space
- First Name, followed by a single space
- Middle Name(optional), followed by a single space
- Last Name(optional)
Examples:
Input : Mr. Albus Severus Potter
Output : Valid
Input : Lily and Mr. Harry Potter
Output : Invalid
Note : Since, we are using IGNORECASE flag, the first character of First, Second, and Last name may or may not be capital.
Below is the Python code –
import re
def validating_name(name):
regex_name = re. compile (r '^(Mr\.|Mrs\.|Ms\.) ([a-z]+)( [a-z]+)*( [a-z]+)*$' ,
re.IGNORECASE)
res = regex_name.search(name)
if res: print ( "Valid" )
else : print ( "Invalid" )
validating_name( 'Mr. Albus Severus Potter' )
validating_name( 'Lily and Mr. Harry Potter' )
validating_name( 'Mr. Cedric' )
validating_name( 'Mr. sirius black' )
|
Output:
Valid
Invalid
Valid
valid
Share your thoughts in the comments
Please Login to comment...