CC Lab task 1
CC Lab task 1
Memoona Amjad
215083
Activity 1:
import re
inputString = "Hello World from Compiler"
pattern = r"\s+"
replacement= " "
result = re.sub(pattern, replacement, inputString)
print("Orignal String: ",inputString)
print("Replacement String: ",result)
Output:
Activity 2:
import re
inputText = input("Enter your input text: ")
words = inputText.split()
operatorPattern = r'^[+\-*/]$'
regex1 = re.compile(operatorPattern)
for word in words:
match1 = regex1.match(word)
if match1:
print("operator is ",word, end="\n ")
else:
print("invalid", word)
Output:
1. What is a regular expression?
Regular expression can be defined as the language or string accepted by finite automata.
These are used to match the character combinations from the strings, in easy words these
are used to match the patterns in the language or to verify the language.
2. Write a regex to match any digit.
r'[0-9]' or \d
3. How would you match a string that starts with "Hello"?
r'^Hello'
4. Explain the difference between * and + in regex.
Both refer to how many times a character can be appeared, + means one or more, while *
means zero or more.
5. Create a regex to validate an email address.
r'^[0-9]{6}@aack\.au\.edu\.pk$'
import re
strings = ["this is a cat", "this is a catalog"]
pattern = r'^(?!.*catalog).*cat.*$'
for string in strings:
if re.match(pattern,string):
print(f"match {string}")
else:
print(f"no match {string}")
import re
pattern = r'\b[aeiouAEIOU]\w*\b'
string = "Apple banana haha ok bye."
matches = re.findall(pattern, string)
print(matches)
9. What is the purpose of parentheses in regex?
For grouping expressions.
10. Explain the use of the ^ and $ anchors.
^ refers to start where $ refers to the end of the pattern or regular expression.