Python uses the RE module to extract the contents of parentheses within a string

Source: Internet
Author: User
This article mainly introduces Python using the RE module to extract the contents of the string in parentheses, in conjunction with the instance of the form of the analysis of Python using the RE module for the parentheses content of the regular matching operation, and simple explanation of the correlation modifier and the use of regular statements, the need for friends can refer to the next

The example in this article is about Python using the RE module to extract the contents of the string within parentheses. Share to everyone for your reference, as follows:

Directly on the code bar:

#-*-Coding:utf-8-*-#! Python2import restring = ' Abe (AC) AD) ' P1 = Re.compile (R ' [(] (. *?) [)] ', Re. S) #最小匹配p2 = Re.compile (R ' [(] (. *) [)] ', Re. S)  #贪婪匹配print (Re.findall (P1, String)) print (Re.findall (P2, String))

Output:

[' AC '] [' AC) ad ']

Explain:

1. The regular matching string was added with R to make the special symbol inside not write back slash.

2.[] has the function of going to special symbols, that is to say [(] (just plain parentheses

3. The regular matching string () is to extract the contents of the entire regular string in accordance with the parentheses.

4: is to represent any character except for the line break. * Colin Closures, appearing 0 or unlimited times.

5. Add it? is the smallest match, not a greedy match.

6. Re. S is to let. Represents any character except the line break.

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.