Home > Backend Development > Python Tutorial > python正则分组的应用

python正则分组的应用

WBOY
Release: 2016-06-16 08:46:15
Original
1467 people have browsed it

复制代码 代码如下:

import re
text='V101_renow.Android.2.2.Normal.1.Alpha.apk?IMSI=460029353813976&MOBILE=&OLD_VERSION=renow.Android.2.1.Normal.1.Alpha&CHANNELID=3'
m = re.search(r"\w+_(renow.*)\.(apk|vir|ipa)\?IMSI=(\d+)&MOBILE=&OLD_VERSION=(.*)&CHANNELID=(.*)", text)
if m:
    print m.group(0), '\n', m.group(1),'\n', m.group(2),'\n', m.group(3),'\n', m.group(4),'\n', m.group(5)
else:
    print 'not match'


以下是补充:

组是通过 "(" 和 ")" 元字符来标识的。 "(" 和 ")" 有很多在数学表达式中相同的意思;它们一起把在它们里面的表达式组成一组。举个例子,你可以用重复限制符,象 *, +, ?, 和 {m,n},来重复组里的内容,比如说(ab)* 将匹配零或更多个重复的 "ab"。

例子:如果不引入括号,增个表达式作为一个组,是group(0)

>>> import re
>>> p=re.compile('\d-\d-\d')
>>> m=p.match('2-3-1')
>>> m.groups()
()
>>> m.group()
'2-3-1'
>>> m.group(1)
Traceback (most recent call last):
  File "", line 1, in
IndexError: no such group

如果引入括号,可以将上面的表达式分成3组,如下

>>> p=re.compile('(\d)-(\d)-(\d)')
>>> m=p.match('1-2-3')
>>> m.group()
'1-2-3'
>>> m.group(1)
'1'
>>> m.group(0,2,1)
('2-3-1', '2', '1')

也可以给各个组取名字,例如,给第一个数组取名叫first


>>> p=re.compile('(?P\d)-(\d)-(\d)')
>>> m=p.match('1-2-3')
>>> m.group(1)
'1'
>>> m.group('first')

'1'

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template