2011-02-14 161 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']