我怎么能得到一个看起来像这样的字符串
string = 'Contact name: John Doe Contact phone: 222-333-4444'
并在两个冒号上拆分字符串?理想情况下,输出看起来像:
['Contact Name', 'John Doe', 'Contact phone','222-333-4444']
真正的问题是名称可以是任意长度但是,我认为可以使用re
在一定数量的空格字符之后拆分字符串(比如至少4个,因为可能总是至少有4个空格)在任何名称的结尾和Contact phone
的开头之间)但我对正则表达式并不是那么好。如果有人可以提供一个可能的解决方案(以及我可以学习的解释),那将非常感激。
你可以使用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