本文实例讲述了Python正则表达式实现截取成对括号的方法。分享给大家供大家参考,具体如下:
1
2
3
4
|
strs = '1(2(3(4(5(67)6)7)8)9)0' reg1 = re. compile ( '([()])∗' ) #一对括号 reg2 = re. compile ( '([()]|\([()]∗)*\)' ) #两对括号 reg3 = re. compile ( '([()]|\([()]∗|([()]|\([()]∗)*\))*\)' ) #三层 |
函数
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#匹配成对括号正则表达式 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 |
希望本文所述对大家Python程序设计有所帮助。