Search code examples
regexpython-3.xregex-lookaroundsregex-groupregex-greedy

How to extract arguments using regex?


I want to extract arguments (type of command-line arguments) using regex. Here i will take the string as input and and get the arguments as groups

Basically i want the set in regex to both exclude and include some characters.

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)

I want the output to be

['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']

but the output is

['m=psrmcc;ld', 'kkk', 'klfj']

Solution

  • You can use re.split

    Ex:

    import re
    
    print(re.split(r"--", "command --m=psrmcc;ld -  --kkk gtodf --klfj")[1:])
    #or
    print("command --m=psrmcc;ld -  --kkk gtodf --klfj".split("--")[1:])
    

    Output:

    ['m=psrmcc;ld -  ', 'kkk gtodf ', 'klfj']