Home > Backend Development > Python Tutorial > Python uses the re module to regularly extract the content within brackets in the string

Python uses the re module to regularly extract the content within brackets in the string

不言
Release: 2018-06-02 14:48:37
Original
2546 people have browsed it

This article mainly introduces Python's use of the re module to regularly extract the content within brackets in a string. It analyzes Python's use of the re module to perform regular matching operations on the content of brackets in the form of examples, and briefly explains the relevant modifiers and regular expressions. For the usage of the statement, friends who need it can refer to

. This article describes the use of the re module in Python to extract the content within the brackets in the string. Share it with everyone for your reference, the details are as follows:

Go directly to the code:

# -*- coding:utf-8 -*-
#! python2
import re
string = '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))
Copy after login

##Output :

['ac']
['ac)ad']
Copy after login

Explanation:

1. The r is added before the regular matching string so that the special symbols inside do not need to be written with backslashes.

2. [ ] has the function of removing special symbols, that is to say, the ( in [(] is just an ordinary bracket

3. The () in the regular matching string is to extract the entire regular expression The content in the string that conforms to the regular expressions in parentheses

4. . is used to represent any character except the newline character. *Klin closure, appearing 0 or infinite times.

5. Adding? is a minimum match, not adding is a greedy match.

6. re.S is to let . represent any character except the newline character.

Related recommendations:

Python uses add_subplot and subplot to draw subplot operations

Python uses the cx_Oracle module to operate Oracle database detailed explanation

The above is the detailed content of Python uses the re module to regularly extract the content within brackets in the string. For more information, please follow other related articles on the PHP Chinese website!

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