在Python中使用多个分隔符分割字符串[重复]

问题描述 投票:0回答:5

我在网上找到了一些答案,但我没有正则表达式的经验,我相信这就是这里所需要的。

我有一个字符串需要用“;”分隔或者 ', ' 也就是说,它必须是分号或逗号,后跟空格。没有尾随空格的单个逗号应保持不变

示例字符串:

"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]') 
python string split delimiter
5个回答
1264
投票

幸运的是,Python 有这个内置功能:)

import re

# Regex pattern splits on substrings "; " and ", "
re.split('; |, ', string_to_split)

更新:

根据您的评论:

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

494
投票

做一个

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


186
投票

对于任何可迭代的分隔符,这是使用正则表达式的安全方法:

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


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

>>> 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?"]

(将

?<=
替换为
?=
,将分隔符附加到右侧,而不是左侧)


95
投票

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

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

40
投票

这就是正则表达式的样子:

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)
© www.soinside.com 2019 - 2024. All rights reserved.