我之前提出了一个问题(Python splitting unknown string by spaces and parentheses),这个问题在我改变思路之前非常好用。但是我仍然没有掌握正则表达式,所以需要一些帮助。
如果用户输入以下内容:
我目前正在使用这段代码,但它不符合上述标准(来自上面链接中的答案):
这很有效但有一个问题,如果你有这个:
如果用户输入以下内容:
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']
这很有效但有一个问题,如果你有这个:
strs = "Hello Test (Test1 test2) (Hello1 hello2) other_stuff"
它会将Hello和Test合并为一个分割而不是两个。
它也不允许同时使用括号和引号进行拆分。