Skip to content

Commit d5267aa

Browse files
committed
add regex hw
1 parent b87d508 commit d5267aa

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

homework/week5/regex/regex.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import re
2+
3+
# Function to match a regular expression pattern in a string
4+
def match_pattern(pattern, text):
5+
"""
6+
Match a regular expression pattern in a given text and return the result.
7+
"""
8+
matches = re.findall(pattern, text)
9+
return matches
10+
11+
# Function to find and replace using regular expressions
12+
def find_and_replace(pattern, replacement, text):
13+
"""
14+
Find and replace all occurrences of a regular expression pattern in a given text with a replacement string.
15+
"""
16+
replaced_text = re.sub(pattern, replacement, text)
17+
return replaced_text
18+
19+
# Function to split a string using a regular expression
20+
def split_text(pattern, text):
21+
"""
22+
Split a text into a list of substrings using a regular expression pattern as the delimiter.
23+
"""
24+
substrings = re.split(pattern, text)
25+
return substrings
26+
27+
# Example usage
28+
if __name__ == "__main__":
29+
# Example text
30+
sample_text = "Hello, my email is john@example.com and my phone number is 123-456-7890."
31+
32+
# 1. Matching a pattern
33+
email_pattern = r'WRITE_HERE'
34+
email_matches = match_pattern(email_pattern, sample_text)
35+
print("Email matches:", email_matches)
36+
37+
# 2. Finding and replacing
38+
phone_pattern = r'WRITE_HERE'
39+
replaced_text = find_and_replace(phone_pattern, "XXX-XXX-XXXX", sample_text)
40+
print("Text after phone number replacement:")
41+
print(replaced_text)
42+
43+
# 3. Splitting text
44+
words_pattern = r'WRITE_HERE'
45+
word_list = split_text(words_pattern, sample_text)
46+
print("Words in the text:", word_list)

0 commit comments

Comments
 (0)