以特殊方式拆分字符串

时间:2017-11-20 18:34:02

标签: python regex

我有一个像str = "3 (15 ounce) cans black beans"这样的字符串。我想将它分成几个部分,用括号术语分割。结果应该是:

['3', '(15 ounce)', 'cans black beans']保留括号。

如何使用Python中的正则表达式实现此目标?

2 个答案:

答案 0 :(得分:2)

尝试将带有[()]的re.split()用作正则表达式。

>>> import re
>>> s = "3 (15 ounce) cans black beans"
>>> re.split(r'[()]', s)
['3 ', '15 ounce', ' cans black beans']
>>> 

>>> help(re.split)

编辑:

要保留括号,您可以执行以下操作:

>>> re.search(r'(.*)(\(.*\))(.*)', s).groups()
('3 ', '(15 ounce)', ' cans black beans')
>>>

答案 1 :(得分:0)

好的,正如Anubhava建议的解决方案是使用re.findall(r'\([^)]*\)|[^()]+', line)

line = '3 (15 ounce) cans black beans, drained and rinsed'
a = re.findall(r'\([^)]*\)|[^()]+', line)

print(a)给出了

['3 ', '(15 ounce)', ' cans black beans, drained and rinsed']

正是我想要的,感谢那些试图帮助我的人:)