正则表达式分割第一个冒号
我有一个符合ISO 8601格式的时间(2009-11-19T19:55:00
),它还和一个名字commence
配对在一起。我想把这个时间和名字分开。目前我已经做到这个步骤:
import re
sColon = re.compile('[:]')
aString = sColon.split("commence:2009-11-19T19:55:00")
显然,这样做的结果是:
>>> aString
['commence','2009-11-19T19','55','00']
我希望得到的结果是这样的:
>>>aString
['commence','2009-11-19T19:55:00']
我该如何在最初创建sColon
的时候做到这一点?另外,你有没有推荐的正则表达式的链接或书籍?我觉得将来可能会用到它!
编辑:
为了更清楚……我需要一个正则表达式,能够在第一个:
出现的地方进行解析,这可能吗?在冒号前面的文本(commence
)是可以变化的,没问题……
4 个回答
0
看起来你需要用 .IndexOf(":") 来找到冒号的位置,然后再用 .Substring() 来截取字符串?
5
你可以在分割函数中设置最大分割参数。
>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']
官方文档
S.split([分隔符 [,最大分割次数]]) -> 字符串列表
Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
5
>>> first, colon, rest = "commence:2009-11-19T19:55:00".partition(':')
>>> print (first, colon, rest)
('commence', ':', '2009-11-19T19:55:00')
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。