通过正则表达式拆分而不会在Python中生成空字符串

时间:2015-06-19 08:13:30

标签: python regex

我想拆分包含不规则重复分隔符的字符串,就像方法split()一样:

>>> ' a b   c  de  '.split()
['a', 'b', 'c', 'de']

然而,当我通过正则表达式应用split时,结果是不同的(空字符串潜入结果列表):

>>> re.split('\s+', ' a b   c  de  ')
['', 'a', 'b', 'c', 'de', '']
>>> re.split('\.+', '.a.b...c..de..')
['', 'a', 'b', 'c', 'de', '']

我想看到的是:

>>>some_smart_split_method('.a.b...c..de..')
['a', 'b', 'c', 'de']

2 个答案:

答案 0 :(得分:4)

空字符串只是正则表达式分割(though there is good reasoning as to why that behavior might be desireable)的必然结果。要摆脱它们,你可以在结果上调用过滤器。

results = re.split(...)
results = list(filter(None, results))

注意list()变换只在Python 3中是必需的 - 在Python 2中,filter()返回一个列表,而在3中它返回一个过滤器对象。

答案 1 :(得分:4)

>>> re.findall(r'\S+', ' a b   c  de  ')
['a', 'b', 'c', 'de']