2017-08-18 148 views
1

我有以下字符串:正則表達式拆分含連字符的單詞串

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"'] 

我缺少什麼?謝謝。

+0

你不只是要分析*字符串文字*? –

+2

嘗試['re.findall(r'「[^」] *「| [^ \ s + - ] +',test_string)'](http://ideone.com/EGvbP4) –

+0

我不認爲這是完全清楚你想要分裂的東西,但是看起來你可能想要考慮使用積極的預見。 – Matthew

回答

1

考慮使用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 ['+', '-']] 

變量:

>>> print(arr) 
['abc', '+', 'def', '+', '-xyz - rst'] 
>>> print(final_arr) 
['abc', 'def', '-xyz - rst'] 
相關問題