通过保留引用的子串的空格将N个元素拆分为一个字符串

Nic*_*las 3 python

我想用空格将一个字符串拆分为3个元素,但我不希望拆分引用的子字符串(它们也可以包含反斜杠来转义引号).

例如:

"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']
Run Code Online (Sandbox Code Playgroud)

我看了一下这个类似的问题,shlex.split()也会拆分字符串的结尾(它将删除引号和空格),而我想保持第三个元素不变.

我试图使用shlex.split(mystring)[0:2]以获得前两个元素,但后来我无法找到一个很好的解决方案从原始字符串中提取第三个元素.实际上我希望我可以使用带参数shlex.split()str.split()方法maxsplit.

有没有比使用更好的方法shlex.split()呢?也许是正则表达式?谢谢!

eca*_*mur 5

您应该能够通过访问shlex对象的解析器状态来破解解决方案:

>>> import shlex
>>> s = shlex.shlex("command 'my \'ugly\' argument' other \"arguments\" and options", posix=True)
>>> s.whitespace_split = True
>>> s.commenters = ''
>>> next(s)
'command'
>>> next(s)
'my ugly argument'
>>> s.instream.read()
'other "arguments" and options'
Run Code Online (Sandbox Code Playgroud)

请参阅shlex.py模块源.