正则表达式拆分包含带连字符的字符串

时间:2017-08-18 22:14:27

标签: regex python-3.x

我有以下字符串:

test_string = '"abc" + "def" + "-xyz - rst"'

我试图仅基于 - 或+运算符拆分此字符串,但从此正则表达式拆分中排除了带连字符的单词。我到目前为止:

In [205]: [n.strip() for n in re.split(r'[ ]{1}[-+]', test_string) if n != '']
Out[205]: ['"abc"', '"def"', '"-xyz', 'rst"']

我期待我的结果是:

In [205]: [n.strip() for n in re.split(r'[ ]{1}[-+]', test_string) if n != '']
Out[205]: ['"abc"', '"def"', '"-xyz - rst"']

我错过了什么?感谢。

1 个答案:

答案 0 :(得分:1)

考虑使用Block.getColor()

shlex

变量:

import shlex
test_string = '"abc" + "def" + "-xyz - rst"'
# Parse the string into space-separated elements treating quotes as the shell does
# lone + and - signs will be their own element
arr = shlex.split(test_string)
# remove any element that is either '+' or '-'
final_arr = [x for x in arr if x not in ['+', '-']]