Replacing repeated captures

后端 未结 4 1890
悲哀的现实
悲哀的现实 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-18 13:19

    You can indeed use the regex module and repeated captures. The main interest is that you can check the structure of the matched string:

    import regex
    
    regO = regex.compile(r'''
        \w+ \( (?: name\['([^']*)'] (?: ,[ ] | (?=\)) ) )* \)
        ''', regex.VERBOSE);
    
    regO.sub(lambda m: 'XYZ(' + (', '.join(m.captures(1))) + ')', s)
    

    (Note that you can replace "name" by \w+ or anything you want without problems.)

提交回复
热议问题