匹配分组

 1 '''
 2 (ab)  将括号中的字符作为一个分组
 3 \num   引用分组num匹配到的字符串
 4 (?P<name>)  分组起组名
 5 (?P=name)   引用别名为name分组匹配到的字符串
 6 '''
 7 import re
 8 print('匹配座机号码')
 9 # 匹配座机号码, 区号{3,4}-电话号码{5,8} 010-43222 4321-343435
10 pattern = r'(\d{3,4})-([1-9]\d{4,7}$)'
11 # 对当前表达式进行分组
12 s = '010-786545'
13 m = re.match(pattern,s)
14 print(m)
15 print(m.group())
16 print(m.group(1))
17 print(m.group(2))
18 print(m.groups()) # 返回一个元组
19 print(m.groups()[0])
20 print(m.groups()[1])
21 
22 print('匹配出网页标签内的数据')
23 pattern = r'<(.+)><(.+)>.+</\2></\1>'
24 s = '<html><head>head部分</head></html>'
25 m = re.match(pattern,s)
26 print(m)
27 #<body><h1><div><div></div></div></h1></body>
28 print('(?P<name>) 分组起组名')
29 pattern = r'<(?P<k_html>.+)><(?P<k_head>.+)>.+</(?P=k_head)></(?P=k_html)>'
30 s = '<html><head>head部分</head></html>'
31 o = re.match(pattern,s)
32 print(o)
 1 匹配座机号码
 2 <re.Match object; span=(0, 10), match='010-786545'>
 3 010-786545
 4 010
 5 786545
 6 ('010', '786545')
 7 010
 8 786545
 9 匹配出网页标签内的数据
10 <re.Match object; span=(0, 32), match='<html><head>head部分</head></html>'>
11 (?P<name>) 分组起组名
12 <re.Match object; span=(0, 32), match='<html><head>head部分</head></html>'>

 

posted @ 2020-05-18 09:45  小他_W  阅读(180)  评论(0编辑  收藏  举报