Python 正则表达式 re模块 groups/group

目录

详细可参考http://funhacks.net/2016/12/27/regular_expression/

1.区分贪婪匹配和非贪婪匹配

2.re的compile方法和re function

3.带表达式的正则表达式

4.groups与group

5.匹配规则



 

详细可参考http://funhacks.net/2016/12/27/regular_expression/

1.区分贪婪匹配和非贪婪匹配

Python 正则表达式 re模块 groups/group

2.re的compile方法和re function

Python 正则表达式 re模块 groups/group

以findall为例:

Python 正则表达式 re模块 groups/group

 

Python 正则表达式 re模块 groups/group

3.带表达式的正则表达式

 for target in targets:
        result[target]=re.search(r'<tr id="places_%s__row">.*?<td class="w2p_fw">(.*?)</td>' % target, html).groups()[0]

target就是一个表达式

4.groups与group

 

group和groups是两个不同的函数。

一般,m.group(N) 返回第N组括号匹配的字符。
而m.group() == m.group(0) == 所有匹配的字符,与括号(用来分组的)无关,这个是API规定的。

m.groups() 返回所有括号匹配的字符,以tuple格式。如果没有括号分组m.groups()就没有返回值
m.groups() == (m.group(1), m.group(2), ...)

或者m.groups()[0] == m.group(1),m.groups()[1] == m.group(2)

  • 括号匹配实例:

下面search有两个括号,括号是用来分组的

str_test='<tr id="places_area__row"><td class="w2p_fl"><label class="readonly" for="places_area" id="places_area__label">Area: </label></td><td class="w2p_fw">7,686,850 square kilometres</td>'

result=re.search(r'<tr id="places_area__row">.*?<td class="(w2p_fw)">(.*?)</td>',str_test)

result.group():
'<tr id="places_area__row"><td class="w2p_fl"><label class="readonly" for="places_area" id="places_area__label">Area: </label></td><td class="w2p_fw">7,686,850 square kilometres</td>'

result.groups()
('w2p_fw', '7,686,850 square kilometres')

result.group(1):
'w2p_fw'

result.group(2)
'7,686,850 square kilometres'

result.groups()[0]
'w2p_fw'

result.groups()[1]
'7,686,850 square kilometres'

5.匹配规则

正则表达式有多种不同的风格,下表列出了适用于 Python 或 Perl 等编程语言的部分元字符以及说明:

Python 正则表达式 re模块 groups/group