首页 > 解决方案 > Building custom configuration parser to read method chaining style of configuration string

问题描述

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

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))

标签: pythonregexconfigparser

解决方案


使用负前瞻表达式来匹配最外面的右括号。

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)

这输出:

abc  
def  1,2
xyz  mnp(okm(params))

推荐阅读