Python regular expressions implement the method of intercepting paired parentheses
- 2020-05-19 05:09:04
- OfStack
This article illustrates how the Python regular expression implementation intercepts paired parentheses. I will share it with you for your reference as follows:
strs = '1(2(3(4(5(67)6)7)8)9)0'
reg1 = re.compile('([()])∗') #1 The parentheses
reg2 = re.compile('([()]|\([()]∗)*\)') # Two pairs of parentheses
reg3 = re.compile('([()]|\([()]∗|([()]|\([()]∗)*\))*\)') #3 layer
function
# Matches paired bracketed regular expressions
def getReg(self, count, bracket = '()'):
leftBracket = bracket[0]
rightBracket = bracket[1]
count -= 1
regBasic = leftBracket + '(?:[^' + leftBracket + rightBracket + '])*' + rightBracket
if count < 0:
regBasic = ''
if count > 0:
for i in xrange(count):
tempNum = regBasic.rfind('*') - 1
regBasic = regBasic[:tempNum] + "|" + regBasic + regBasic[tempNum:]
return regBasic
PS: here are two more handy regular expression tools for you to use:
JavaScript regular expression online testing tool:
http://tools.ofstack.com/regex/javascript
Online regular expression generation tool:
http://tools.ofstack.com/regex/create_reg
More about Python related content to view this site project: the Python regular expression usage summary ", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"
I hope this article is helpful for you to design Python program.