Object Oriented Programming Lab 11
Object Oriented Programming Lab 11
Lab No. 11
Lab 05 – Introduction to Regular Expression
Objectives:
a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in
wild card.
b) Literals (like a,b,1,2…)
1. re.match()
2. re.search()
3. re.findall()
4. re.split()
5. re.sub()
6. re.compile
3. Metacharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of
metacharacters:
[] . ^ $ * + ? {} () \ |
Character Description Example
You can also specify a range of characters using - inside square brackets.
import re
1. re.search()
Function will search the regular expression pattern and return the first occurrence. the
pattern is found and “null” if the pattern is not found
In order to use search() function, you need to import re first and then execute the code.
The search() function takes the "pattern" and "text" to scan from our main string
if match:
print("pattern found inside the string")
else:
print("pattern not found")
Output:
Exercise 2: Write a code that will able to extract ou from all the words in the string.
import re
str = " The rain in Spain"
x = re.findall("Sp", str)
print(x)
Output:
The list contains the matches in the order they are found. If no matches are found, an empty list
is returned.
Exercise 3:
import re
Output:
4. re.split()
The re.split method splits the string where there is a match and returns a list of strings
where the splits have occurred.
If there is more than one match, only the first occurrence of the match will be returned:
Exercise 4:
import re
Output:
The method returns a string where matched occurrences are replaced with the content of
replace variable
Exercise 6:
# Program to remove all whitespaces
import re
# multiline string
string = 'abc 12\
Prepared By: Syed CS-121 | Object Oriented 7
Faisal Ali Programming
May 15, 2019 Lab 09 – Introduction to Regular Expression
# empty string
replace = ''
Output:
Task1:
You are working in Data Science project in which you need to find the mobile networks in
certain area.
For this your task is to enter at least 10 mobile numbers in a file of different companies based on
list provided to you. Extract the mobile numers such as 0332 is for Ufone, then at the end of the
list calculate each mobile network in total. The required output will be:
After 10 entries
The total will be
Ufone Users :4
Jazz Users 3
Telenor Users 2
Warid Users 1
Total Users : 10