Python通过括号分割字符串

Tre*_*ton 4 python string split

不久前我问了一个问题(Python用空格和括号将未知字符串分割开),在我不得不改变思维方式之前,它一直很有效。我还没有掌握正则表达式,因此我需要一些帮助。

如果用户键入以下内容:

new test (test1 test2 test3) test "test5 test6"

我希望它看起来像这样的变量输出:

["new", "test", "test1 test2 test3", "test", "test5 test6"]

换句话说,如果一个单词用空格分隔,则将其与下一个单词分开;如果在括号中,则将括号中的整个单词组分开并删除它们。引号也是如此。

我目前正在使用的代码不符合上述标准(来自上面链接的答案):

>>>import re
>>>strs = "Hello (Test1 test2) (Hello1 hello2) other_stuff"
>>>[", ".join(x.split()) for x in re.split(r'[()]',strs) if x.strip()]
>>>['Hello', 'Test1, test2', 'Hello1, hello2', 'other_stuff']
Run Code Online (Sandbox Code Playgroud)

这很好用,但是如果有这样的话,那就是一个问题:

strs = "Hello Test (Test1 test2) (Hello1 hello2) other_stuff"

它将Hello和Test合并为一个拆分而不是两个拆分。

它还不允许同时使用括号和引号。

Tre*_*ton 5

答案很简单:

re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+',strs)
Run Code Online (Sandbox Code Playgroud)