0

I am building a configuration parser where using regex I will read a string configuration in the form of

  • method chaining and
  • method calls as parameters inside another methods.

code that will read the configuration and prints them:-

r1 = re.findall(r".\b(start|abc|def|mnp|xyz|okm)\((.*?)\)", string_expr)
for pair in r1:
    operator_name = pair[0]
    operator_param = pair[1]
    print(operator_name,'',operator_param)

The below string_expr works fine for the regex, So I get the desired output.

string_expr:-
start().abc().def(1,2).xyz(params)

output:-
abc
def 1,2
xyz params

The issue here is whenever there is any () data inside the parenethesis, then I am not getting the whole parameter.

string_expr:-start().abc().def(1,2).xyz(mnp(okm(params)))

output:-
abc
def 1,2
xyz mnp(okm(params

instead what I want is xyz mnp(okm(params))

dks551
  • 1,113
  • 1
  • 15
  • 39

1 Answers1

1

Use a negative lookahead expression to match the outermost right parenthesis.

import re
r1 = re.findall(r".\b(start|abc|def|mnp|xyz|okm)\((.*?)\)(?![^(]*\))", 'start().abc().def(1,2).xyz(mnp(okm(params)))')
for pair in r1:
    operator_name = pair[0]
    operator_param = pair[1]
    print(operator_name,'',operator_param)

This outputs:

abc  
def  1,2
xyz  mnp(okm(params))
blhsing
  • 91,368
  • 6
  • 71
  • 106