9.RegEx
9.RegEx
(re)
in Python
Regex
Problem
• Invalid
• Alphabets are not allowed
Test Case 2
• 440446845
• Invalid
• Only 9 digits
Test Case 3
• 0440446845
• Invalid
• Should not begin with a zero
Test Case 4
• 8440446845
• Valid
• All conditions satisfied
Python code to check validity of mobile number (Long
Code)
import sys
number = input()
if len(number)!=10:
print ('invalid')
sys.exit()
elif number[0]=='0':
print ('invalid')
sys.exit()
else:
for chr in number:
if (chr.isdigit()==False):
print ('invalid')
sys.exit()
sys.exit()
Note: The character . matches any single character except a newline character.
•Note Some of the whitespace character are
space/tab/new line
The findall() Function
['ai', 'ai']
text = "test cat testing scatter"
<class 're.Match'>
The first white-space character is located in position: 3
The match() Function
• re.match(pattern, string): This function checks for a match only at
the beginning of the string. If the pattern matches the start of the
string, it returns a match object; otherwise, it returns None.
SYNTAX re.match(pattern,source_string)
if m:
print("Full name:", m.group('user'))
print("website:", m.group('website'))
#Ouput
Full name: myname
website: hackerrank
Matching Any Single Character (.)
[dn]ot* Do,no,dot,dottt
[a-zA-Z_][0-9a-zA-Z_]* or [a-zA-Z_]\w*
re.findall('[ab\-c]', '123-456')
Output ['-']
re.findall('[a-c]', 'abdc')
Output ['a', 'b', 'c']
Flags