分割的文本包含空格,但将引号内的单词保持为一个单位

问题描述 投票:0回答:4

我想将文本拆分为列表,其中带空格的文件名应视为一个项目:示例

s = 'cmd -a -b -c "file with spaces.mp4" -e -f'.split()
print(s)

输出:

['cmd', '-a', '-b', '-c', '"file', 'with', 'spaces.mp4"', '-e', '-f']

期望的输出:

['cmd', '-a', '-b', '-c', '"file with spaces.mp4"', '-e', '-f']

我尝试过使用一些for循环,但是很讨厌,是否有使用正则表达式或其他看起来不太丑的方法?

python regex
4个回答
4
投票

实际上,在这种情况下,我将不使用正则表达式。这是shlex.split()的用途:

shlex.split()

打印:

import shlex

s = shlex.split( 'cmd -a -b -c "file with spaces.mp4" -e -f' )
print(s)

4
投票

尝试['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']

shlex

收益率,

import shlex

data=('cmd -a -b -c "file with spaces.mp4" -e -f')

new=shlex.split(data)

print(new)

3
投票

这可以通过内置的['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f'] 模块来完成,例如:

shlex

import shlex s = shlex.split('cmd -a -b -c "file with spaces.mp4" -e -f', posix=False) print(s) 传递给posix=False的目的是保留多字文件名周围的引号,因为所需的输出格式是这样的。如果您不想保留引号,则可以删除split参数。


0
投票

使用正则表达式匹配:

  • [posix最终后跟另一个""),或
  • 任何非空格字符("[^"]*"):
\S+
© www.soinside.com 2019 - 2024. All rights reserved.