2017-08-18 10 views
1

を含む文字列に分割します。私はこれまでのところ得た:正規表現は、私は次の文字列を持っているハイフネーションされた単語

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'] 
関連する問題