I would like to split a string into 3 elements by spaces but I don't want the quoted substrings to be split (they can also contain backslash to escape the quotes).
For instance:
"command argument other arguments and options"
>> ['command', 'argument', 'other arguments and options']
'command "my argument" other arguments and options'
>> ['command', 'my argument', 'other arguments and options']
'command "my \"ugly\" argument" other "arguments" and options'
>> ['command', 'my "ugly" argument', 'other "arguments" and options']
I had a look at this similar question but shlex.split()
will also split the end of the string (and it will remove the quotes and the spaces) whereas I want to keep the third element intact.
I tried to use shlex.split(mystring)[0:2]
in order to get the first two elements but then I can't manage to find a good solution to extract the third element from the original string. Actually I wish I could use shlex.split()
like the str.split()
method with a maxsplit
argument.
Is there a better way to do this than using shlex.split()
? Perhaps regexes? Thanks!