2011-02-14 267 views
270

我在网上找到了一些答案,但我没有使用正则表达式的经验,我相信这里是需要的。Python:分割字符串与多个分隔符

我有一个字符串,需要通过';'拆分,或',' 也就是说,它必须是分号或逗号,后跟空格。没有尾部空格个体逗号应当保持不变

例字符串:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]" 

应分成含有如下的列表:

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') 

回答

459

幸运的是,Python有此内置:)

import re 
re.split('; |, ',str) 

更新:
按照您的评论:

>>> a='Beautiful, is; better*than\nugly' 
>>> import re 
>>> re.split('; |, |\*|\n',a) 
['Beautiful', 'is', 'better', 'than', 'ugly'] 
103

做一个str.replace('; ', ', ')然后str.split(', ')

+6

+1;非常具体和重点,而不是通用的。这通常更好。 – 2012-09-06 09:22:11

+30

假设你有5个分位数,你必须遍历你的字符串5倍的次数 – 2012-09-26 23:23:28

+0

这对性能非常不利 – 2012-11-26 18:04:42

19

这是正则表达式的样子:

import re 
# "semicolon or (a comma followed by a space)" 
pattern = re.compile(r";|, ") 

# "(semicolon or a comma) followed by a space" 
pattern = re.compile(r"[;,] ") 

print pattern.split(text) 
59

下面是分隔符的任何可迭代一种安全的方式,使用常规表情:

>>> import re 
>>> delimiters = "a", "...", "(c)" 
>>> example = "stackoverflow (c) is awesome... isn't it?" 
>>> regexPattern = '|'.join(map(re.escape, delimiters)) 
>>> regexPattern 
'a|\\.\\.\\.|\\(c\\)' 
>>> re.split(regexPattern, example) 
['st', 'ckoverflow ', ' is ', 'wesome', " isn't it?"] 

re.escape允许自动构建模式并使分隔符很好地逃脱。

下面是该解决方案为您的复制粘贴乐趣的功能:

def split(delimiters, string, maxsplit=0): 
    import re 
    regexPattern = '|'.join(map(re.escape, delimiters)) 
    return re.split(regexPattern, string, maxsplit) 

如果你打算分割往往使用相同的分隔符,编译正则表达式像事先说明并使用RegexObject.split

36

回应上面的Jonathan的回答,这似乎只适用于某些分隔符。例如:

>>> a='Beautiful, is; better*than\nugly' 
>>> import re 
>>> re.split('; |, |\*|\n',a) 
['Beautiful', 'is', 'better', 'than', 'ugly'] 

>>> b='1999-05-03 10:37:00' 
>>> re.split('- :', b) 
['1999-05-03 10:37:00'] 

通过将分隔符方括号中似乎更有效地工作。

>>> re.split('[- :]', b) 
['1999', '05', '03', '10', '37', '00']