Python USES the re module to regularly extract the contents of parentheses in a string as an example
- 2020-10-31 21:50:26
- OfStack
This article is an example of how Python USES the re module to regularly extract the contents of parentheses in a string. To share for your reference, the details are as follows:
Just code it:
# -*- coding:utf-8 -*-
#! python2
import re
string = 'abe(ac)ad)'
p1 = re.compile(r'[(](.*?)[)]', re.S) # The minimum matching
p2 = re.compile(r'[(](.*)[)]', re.S) # Greed match
print(re.findall(p1, string))
print(re.findall(p2, string))
Output:
[
['ac']
['ac)ad']
Explain 1 below:
1. r is added before the regular match string so that the special symbol does not have to be backslashes.
2.[] has the function of eliminating special symbols, that is, the (in [() is just a trivial parenthesis
3. The () in the regular match string is to extract the regular content in the whole regular string that conforms to the regular content in parentheses
4. Is used to represent any 1 character other than a newline character. * Kling closure, 0 or infinite occurrences.
5. Add? It's a minimum match, no plus it's a greedy match.
6. re.S is for let. Represents any 1 character other than a newline character.
PS: Here are two more handy regular expression tools for you to use:
JavaScript Regular Expression online test tool:
http://tools.ofstack.com/regex/javascript
Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg
For more information about Python, please visit Python Regular Expression Usage Summary, Python Data Structure and Algorithm Tutorial, Python Function Usage Tips summary, Python String Manipulation Tips Summary, Python Introductory and Advanced Classic Tutorial and Python File and Directory Manipulation Tips Summary.
I hope this article has helped you with Python programming.