我刚才问了一个问题 ( Python splitting unknown string by spaces and parentheses ),在我不得不改变我的思维方式之前,这个问题一直很有效。我还没有掌握正则表达式,所以我需要一些帮助。
如果用户输入:
新测试(test1 test2 test3)测试“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 = "你好测试 (Test1 test2) (Hello1 hello2) other_stuff"
它将 Hello 和 Test 合并为一个而不是两个。
也不允许同时使用括号和引号分割。
最佳答案
答案很简单:
re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+',strs)
关于Python 用括号分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352321/