-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelpful regex.py
52 lines (33 loc) · 1.39 KB
/
helpful regex.py
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
import re
statement = 'Please contact us at: [email protected]'
match = re.search(r'([\w-]+)@([\w-]+)', statement)
if statement:
print("Email address:", match.group())
print("Username:", match.group(1))
print("Host:", match.group(2))
# you can also create named
statement = 'Please contact us at: [email protected]'
match2 = re.search(r'(?P<email>(?P<username>[\w-]+)@(?P<host>[\w-]+))', statement)
if statement:
print("Email address:", match2.group("email"))
print("Username:", match2.group("username"))
print("Host:", match2.group("host"))
# compliling demo match string into regular expression object
pattern = re.compile(r'(?P<email>(?P<username>[\w-]+)@(?P<host>[\w-]+))')
match3 = pattern.search(statement)
if statement:
print("Email address:", match3.group("email"))
print("Username:", match3.group("username"))
print("Host:", match3.group("host"))
#findall in re
statement = "Please contact us at: [email protected], [email protected]"
emails = re.findall(r'[\w\.-]+@[\w\.-]+', statement)
# Finds all the possible matches in the entire sequence and returns them
# as a list of strings. Each returned string represents one match.
for email in emails:
print(email)
pattern = re.compile('COOKIE', re.IGNORECASE)
match = pattern.search("I am not a cookie monster")
print("Start index:", match.start())
print("End index:", match.end())
print("Tuple:", match.span())