Python - 拆分多次出现相同分隔符的字符串

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

我怎么能得到一个看起来像这样的字符串

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

并在两个冒号上拆分字符串?理想情况下,输出看起来像:

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

真正的问题是名称可以是任意长度但是,我认为可以使用re在一定数量的空格字符之后拆分字符串(比如至少4个,因为可能总是至少有4个空格)在任何名称的结尾和Contact phone的开头之间)但我对正则表达式并不是那么好。如果有人可以提供一个可能的解决方案(以及我可以学习的解释),那将非常感激。

python regex string
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.