-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathlearn_regex.py
More file actions
73 lines (50 loc) · 1.78 KB
/
learn_regex.py
File metadata and controls
73 lines (50 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import re
text = "Data science is cool as you get to work with real-world data"
matches = re.findall(r"data", text)
print(matches)
matches = re.findall(r"data", text, re.IGNORECASE)
print(matches)
text = "The cat sat on the mat. The bat flew over the rat."
pattern = r"The ... "
matches = re.findall(pattern, text)
print(matches)
text = "The cat sat on the mat. The bat flew over the rat."
pattern = r"[cb]at"
matches = re.findall(pattern, text)
print(matches)
# Find all lowercase words that start with a-d
pattern = r"\b[a-d][a-z]*\b"
text = "apple banana cherry date elephant fig grape kiwi lemon mango orange"
matches = re.findall(pattern, text)
print(matches)
text = "Contact: john.doe@example.com"
pattern = r"(?P[\w.]+)@(?P[\w.]+)"
match = re.search(pattern, text)
if match:
print(f"Username: {match.group('username')}")
print(f"Domain: {match.group('domain')}")
text = "Phone numbers: 555-1234, 555-5678, 5551234"
pattern = r"\b\d{3}-?\d{4}\b"
matches = re.findall(pattern, text)
print(matches)
text = "Python is popular in data science."
# ^ anchors to the start of the string
start_matches = re.findall(r"^Python", text)
print(start_matches)
# $ anchors to the end of the string
end_matches = re.findall(r"science\.$", text)
print(end_matches)
text = "Dates: 2023-10-15, 2022-05-22"
pattern = r"(\d{4})-(\d{2})-(\d{2})"
# findall returns tuples of the captured groups
matches = re.findall(pattern, text)
print(matches)
# You can use these to create structured data
for year, month, day in matches:
print(f"Year: {year}, Month: {month}, Day: {day}")
text = "Contact: john.doe@example.com"
pattern = r"(?P[\w.]+)@(?P[\w.]+)"
match = re.search(pattern, text)
if match:
print(f"Username: {match.group('username')}")
print(f"Domain: {match.group('domain')}")