在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]')
1250114 次浏览

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

这就是regex的样子:

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)

幸运的是,Python内置了这个:)

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

更新时间:
在您的评论之后:

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

以下是使用正则表达式的任何分隔符可迭代的安全方法:

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

re.escape允许自动构建模式并很好地转义分隔符。

以下是这个解决方案,作为您复制粘贴乐趣的功能:

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

如果您要经常使用相同的分隔符进行拆分,请像所描述的那样事先编译正则表达式并使用RegexObject.split


如果您想在字符串中保留原始分隔符,您可以更改正则表达式以使用后向断言

>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regex_pattern = '|'.join('(?<={})'.format(re.escape(delim)) for delim in delimiters)
>>> regex_pattern
'(?<=a)|(?<=\\.\\.\\.)|(?<=\\(c\\))'
>>> re.split(regex_pattern, example)
['sta', 'ckoverflow (c)', ' is a', 'wesome...', " isn't it?"]

(将?<=替换为?=以将分隔符连接到右侧,而不是左侧)

>>> 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']