In: Computer Science
Understanding RegEx to identify patterns of data.
1. Create 4 regular expressions to filter a specific data set.
2. In addition to the description, provide two test cases that will pass the input and one that will fail
A sample text string where regular expression
1.>
Program : To search digit in string using regular expression in python
import re
string = """ Hello i am vikash , my age is 25 yrs and my area code
is
90123 ans i like the number 890 along with this i live in
sector 345 kth block. """
# A sample regular expression to find digits.
regex = '\d+'
match = re.findall(regex, string)
print(match)
OUTPUT:
['25', '90123', '890', '345']
2.> To check if word starts with "The" or not using regex
import re
string = "The time is very crucial for health in this pendamic"
#checking whether string starts with "the" or not
x = re.findall("\AThe",string)
print(x)
if x:
print("Yes, match is there")
else:
print("No match")
3.>To match alpha numeric characters in a given string we uses “^w+”:
import re
string= "vikash22 is my user id"
r1 = re.findall(r"^\w+",string)
print(r1)
# if we execute it will give result as vikash22 because it will only matches alphanumeric character (which contains alphabet or numbers) and matches with starting character , if matched found it will return . here ^ ensure that alphanumeric should be in starting of string.
output :
['vikash22']
4.> Regex for finding all capital letters character present in the string we uses [A-Z]+ it will gives ll the Capital letters that matches 1 or more times .
#This regex [A-Z]+ gives all Capital letters in the given
string
import re
string= "VikaSh Is My90 User ID"
r1 = re.findall(r"[A-Z]+",string)
print(r1)
OUTPUT
['V', 'S', 'I', 'M', 'U', 'ID']
Concepts used in Regex :
Some important regex functions like
-> re.findall( ) : It will gives us the list of all matching patterns in the form of list as output
-> re.search( ) : It will search if the patterns matches using the given regex or not , if matches return True else return false.
-> re.match( ) : This function will search the regular expression pattern and return the first occurrence when it is found.