Home  >  Article  >  Backend Development  >  Python regular expression method to intercept pairs of brackets

Python regular expression method to intercept pairs of brackets

高洛峰
高洛峰Original
2017-01-12 16:38:062100browse

The example of this article describes the method of intercepting pairs of brackets using Python regular expressions. Share it with everyone for your reference, as follows:

strs = '1(2(3(4(5(67)6)7)8)9)0'
reg1 = re.compile('([()])∗') #一对括号
reg2 = re.compile('([()]|\([()]∗)*\)') #两对括号
reg3 = re.compile('([()]|\([()]∗|([()]|\([()]∗)*\))*\)') #三层

Function

#匹配成对括号正则表达式
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

I hope this article will be helpful to everyone in Python programming.

For more related articles on how to use Python regular expressions to intercept pairs of brackets, please pay attention to the PHP Chinese website!

Statement:
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