Replacing repeated captures

后端 未结 4 1886
悲哀的现实
悲哀的现实 2021-02-18 13:11

This is sort of a follow-up to Python regex - Replace single quotes and brackets thread.

The task:

Sample input strings:

RSQ(nam         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-18 13:32

    Please do not do this in any code I have to maintain.

    You are trying to parse syntactically valid Python. Use ast for that. It's more readable, easier to extend to new syntax, and won't fall apart on some weird corner case.

    Working sample:

    from ast import parse
    
    l = [
        "RSQ(name['BAKD DK'], name['A DKJ'])",
        "SMT(name['BAKD DK'], name['A DKJ'], name['S QRT'])"
    ]
    
    for item in l:
        tree = parse(item)
        args = [arg.slice.value.s for arg in tree.body[0].value.args]
    
        output = "XYZ({})".format(", ".join(args))
        print(output)
    

    Prints:

    XYZ(BAKD DK, A DKJ)
    XYZ(BAKD DK, A DKJ, S QRT)
    

提交回复
热议问题