Python-分割具有多个相同定界符的字符串

时间:2018-06-28 20:08:40

标签: python regex string

如何获取一个像这样的字符串

string = 'Contact name: John Doe                     Contact phone: 222-333-4444'

并在两个冒号上分割字符串?理想情况下,输出应如下所示:

['Contact Name', 'John Doe', 'Contact phone','222-333-4444']

真正的问题是名称可以是任意长度,但是,我认为可以使用re在一定数量的空格字符后分割字符串(例如至少4个,因为这样会在任何名称的末尾与Contact phone的开头之间可能总是至少有4个空格),但是使用regex并不是很好。如果有人可以提供可能的解决方案(和解释以便我学习),将不胜感激。

1 个答案:

答案 0 :(得分:6)

您可以使用re.split

import re
s = 'Contact name: John Doe                     Contact phone: 222-333-4444'
new_s = re.split(':\s|\s{2,}', s)

输出:

['Contact name', 'John Doe', 'Contact phone', '222-333-4444']

正则表达式说明:

:\s => matches an occurrence of ': '
| => evaluated as 'or', attempts to match either the pattern before or after it
\s{2,} => matches two or more whitespace characters
相关问题