The regular expression Python splits the string

What should I do if the

string is split into two parts in front of parentheses and in parentheses?
for example,
ABC1.1 (1) is split into ABC1.1 and 1
% DEF2.1 (3) is split into% DEF2.1 and 3
@ I GHI3.3 O GHI3.3 (5) is split into @ I GHI3.3 O GHI3.3 and 5


import re

matchObj = re.match(r'(.+)\((\d)\)','ABC1.1(1)')
if matchObj:
   print("matchObj.group() : ", matchObj.group())
   print("matchObj.group(1) : ", matchObj.group(1))
   print("matchObj.group(2) : ", matchObj.group(2))

segment_test = re.compile(r'(.*)\((.*)\)')
match = segment_test.match('%DEF2.1(3)')
print match.group()
print match.group(1)
print match.group(2)

View the matching result

regularization is as follows [I can't py, but can only give regularization]:

([^()]+)\(([^()]*)\)

or directly, replace it with empty


>>>import re
>>>pattern = re.compile(r"(.*?)\((.*?)\)", flags=re.DOTALL)
>>>pattern.findall("@ I/O GHI3.3(5)")
[('@ I/O GHI3.3', '5')]
>>>pattern.findall("ABC1.1(1)")
[('ABC1.1', '1')]
>>>pattern.findall("%DEF2.1(3) ABC1.1(1) @ I/O GHI3.3(5) ")
[('%DEF2.1', '3'), (' ABC1.1', '1'), (' @ I/O GHI3.3', '5')]

import re
s1 = 'ABC1.1(1)'
s2 = '%DEF2.1(3)'
s3 = '@ I/O GHI3.3(5) '
r1 = re.split('\(|\)', s1)
print(r1[0] , r1[1]) 
r2 = re.split('\(|\)', s2)
print(r2[0] , r2[1])
r3 = re.split('\(|\)', s3)
print(r3[0] , r3[1])
Menu