可能重复:
Split a string by spaces — preserving quoted substrings — in Python
给出以下字符串:
term1 term2 "the second term has spaces" term3 bad term 4
正则表达式会给我这个列表:
["term1", "term2", "the second term has spaces", "term3", "bad", "term", "4"]
答案 0 :(得分:1)
对于您的简单示例,这样可以正常工作:
import re
quotestring = 'term1 term2 "the second term has spaces" term3 bad term 4'
# uses a lookahead and lookbehind to check for quoted strings
stringlist = re.findall(r'((?<=\").+(?=\")|\w+)', quotestring)
print(stringlist) # works on Python 2 or 3
或者,来自链接的帖子:
import shlex
quotestring = 'term1 term2 "the second term has spaces" term3 bad term 4'
stringlist = shlex.split(quotestring)
print(stringlist)