In: Computer Science
Q1 Write a python regular expression to match a certain pattern of phone number.
### Suppose we want to recognize phone numbers with or without hyphens. The
### regular expression you give should work for any number of groups of any (non-
### empty) size, separated by 1 hyphen. Each group is [0-9]+.
### Hint: Accept "5" but not "-6"
### FSM for TELEPHONE NUMBER IS:
# state:1 --[0-9]--> state:2
# state:2 --[0-9]--> state:4
# state:2 --[\-]---> state:3
# state:3 --[0-9]--> state:4
# state:4 --[\-]---> state:3
# state:4 --[0-9]--> state:4
import re
regexp = ###Your Regular Expression Here.
### regexp matches:
print(re.findall(regexp,"123-4567") == ["123-4567"])
#>>> True
print(re.findall(regexp,"1234567") == ["1234567"])
#>>> True
print(re.findall(regexp,"08-78-88-88-88") == ["08-78-88-88-88"])
#>>> True
print(re.findall(regexp,"0878888888") == ["0878888888"])
#>>> True
### regexp does not match:
print(re.findall(regexp,"-6") != ["-6"])
#>>> True
RAW CODE
import re
regexp = '[^-][0-9-]+' ###Your Regular Expression Here.
### regexp matches:
print(re.findall(regexp,"123-4567") == ["123-4567"])
#>>> True
print(re.findall(regexp,"1234567") == ["1234567"])
#>>> True
print(re.findall(regexp,"08-78-88-88-88") == ["08-78-88-88-88"])
#>>> True
print(re.findall(regexp,"0878888888") == ["0878888888"])
#>>> True
### regexp does not match:
print(re.findall(regexp,"-6") != ["-6"])
#>>> True
SCREENSHOTS (CODE AND OUTPUT)
NOTE:- Here ' [^-] ' represents that should not start with ' - '. ' [0-9-]+ ' represents combination of numbers from 0-9 along with ' - ' anywhere in between and plus represents all the combinations except null value.
##### FOR ANY QUERY, KINDLY GET BACK, THANKYOU. #####