1 '''
2 正则表达式的方法
3 '''
4
5 import re # 0. 导入正则模块
6
7 '''
8 1. 使用re.search()方法进行搜索匹配
9 1. 预编译正则表达式模式:如果你需要多次使用同一个正则表达式模式,建议使用re.compile()方法预先编译该模式(# 预编译正则表达式模式regex = re.compile(pattern)),以提高性能。
10 2. 使用原始字符串:为了避免转义字符的困扰,建议将正则表达式模式定义为原始字符串(在前面加上r)。
11 3. 检查匹配结果:在调用re.search()方法后,应该检查返回的匹配结果是否为None,以确保找到了匹配项。
12 '''
13
14 pattern = r"apple"
15 string = "I have an apple."
16 match = re.search(pattern, string)
17 if match:
18 print("Match found!")
19 else:
20 print("Match not found.")
21
22
23 # 正则模式,此处使用的字面量
24 pattern = r"apple"
25 string = "I have an apple." # 待搜索的字符串
26
27 # 预编译正则表达式模式
28 regex = re.compile(pattern)
29 print(type(regex)) # <class 're.Pattern'>
30 # 使用search方法进行匹配
31 match = regex.search(string)
32 print(type(match)) # <class 're.Match'>
33 if match:
34 print("Match found!")
35 else:
36 print("Match not found.")
37
38
39 # 2. 使用re.match()方法从字符串的开头开始匹配
40 pattern = r"apple"
41 string = "I have an apple."
42 match = re.match(pattern, string)
43 if match:
44 print("Match found!")
45 else:
46 print("Match not found.")
47
48 # 3. 使用re.findall()方法找到所有匹配的字符串:
49 pattern = r"apple"
50 string = "I have an apple. I also have an apple pie."
51 matches = re.findall(pattern, string)
52 print(matches) # 输出: ['apple', 'apple']
53
54
55 # 4. 使用re.sub()方法替换匹配的字符串:
56 pattern = r"apple"
57 string = "I have an apple. I also have an apple pie."
58 new_string = re.sub(pattern, "orange", string)
59 print(new_string) # 输出: "I have an orange. I also have an orange pie."
60
61 # 5. 使用正则表达式中的元字符来定义更复杂的模式:
62 # 匹配一个数字
63 pattern = r"\d"
64 string = "I have 2 apples."
65 match = re.search(pattern, string)
66 if match:
67 print("Match found!")
68 else:
69 print("Match not found.")