Application of Python regular grouping

Source: Internet
Author: User
Copy CodeThe code is as follows:


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 '



Here are the additions:

Groups are identified by the "(" and ")" meta-characters. "(" and ")" have many of the same meanings in mathematical expressions; together they make up a group of expressions within them. For example, you can repeat the contents of the group with a repeating limiter, like *, +,?, and {m,n}, for example (AB) * will match 0 or more duplicate "AB".

Example: If you do not introduce parentheses, add an expression as a group, which is 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):
File " ", line 1, in
Indexerror:no such group

If you introduce parentheses, you can divide the above expression into 3 groups, as follows

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

You can also give names to individual groups, for example, to first array name


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

' 1 '

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.