我在网上找到了一些答案,但我没有正则表达式的经验,我相信这是这里所需要的。
我有一个字符串需要用';'或','分开
也就是说,它必须是分号或逗号后面跟着一个空格。没有结尾空格的单个逗号应该保持不变
示例字符串:
"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]')
下面是使用正则表达式的任何分隔符iterable的安全方法:
>>> 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?"]
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?"]
(将?<=替换为?=以将分隔符附加到右侧,而不是左侧)
针对上面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']
下面是使用正则表达式的任何分隔符iterable的安全方法:
>>> 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?"]
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?"]
(将?<=替换为?=以将分隔符附加到右侧,而不是左侧)
幸运的是,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']