首页 » Python » python 基础 re模块 正则中的组匹配和贪婪非贪婪

python 基础 re模块 正则中的组匹配和贪婪非贪婪

 
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
import re
'''
search 只匹配一个
findall 匹配所有
match
'''

s = 'this is phone:13888888888 and this is my postcode:012345'
reg = 'this is phone:(\d{11}) and this is my postcode:(\d{6})'
result = re.search(reg,s) # <re.Match object; span=(0, 56), match='this is phone:13888888888 and this is my postcode>
print(result)
result = re.search(reg,s).group(0) # this is phone:13888888888 and this is my postcode:012345
print(result)
result = re.search(reg,s).group(1)  # 13888888888
print(result)
result = re.search(reg,s).group(2)  # 012345
print(result)

reg_string = 'HelloPythonHelloString'
reg = 'Hello'
result = re.match(reg,reg_string)  # <re.Match object; span=(0, 5), match='Hello'>
print(result)
result = re.match(reg,reg_string,re.I).group()  # Hello
print(result)
result = re.findall(reg,reg_string)  # ['Hello', 'Hello']
print(result)
result = re.search(reg,reg_string).group()  # Hello
print(result)

# 贪婪与非贪婪
'''
什么是贪婪:尽可能多的匹配
非贪婪:尽可能少的匹配
* 重复零次或更多次 ? 0次
+ 重复一次或更多次 ? 1次
? 重复零次或一次? 0次
'''

reg_string = 'pythonnnnnnnnnpythonHelloPytho'
reg = 'python*'
reg1 = 'python*?'
reg2 = 'python+'
reg3 = 'python+?'
reg4 = 'python?'
reg5 = 'python??'
print(re.findall(reg,reg_string))  # ['pythonnnnnnnnn', 'python']
print(re.findall(reg1,reg_string))  # ['pytho', 'pytho']
print(re.findall(reg2,reg_string))  # ['pythonnnnnnnnn', 'python']
print(re.findall(reg3,reg_string))  # ['python', 'python']
print(re.findall(reg4,reg_string))  # ['python', 'python']
print(re.findall(reg5,reg_string))  # ['pytho', 'pytho']

原文链接:python 基础 re模块 正则中的组匹配和贪婪非贪婪,转载请注明来源!

0