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

Python regular expression method to intercept pairs of brackets

高洛峰
Release: 2017-01-12 16:38:06
Original
2253 people have browsed it

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('([()]|\([()]∗|([()]|\([()]∗)*\))*\)') #三层
Copy after login

Function

#匹配成对括号正则表达式
def getReg(self, count, bracket = '()'):
    leftBracket = bracket[0]
    rightBracket = bracket[1]
    count -= 1
    regBasic = leftBracket + '(?:[^' + leftBracket + rightBracket + '])*' + rightBracket
    if count < 0:
      regBasic = &#39;&#39;
    if count > 0:
      for i in xrange(count):
        tempNum = regBasic.rfind(&#39;*&#39;) - 1
        regBasic = regBasic[:tempNum] + "|" + regBasic + regBasic[tempNum:]
    return regBasic
Copy after login

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!

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