正则表达分裂第一科隆

时间:2009-11-20 13:56:32

标签: python regex

我有时间在ISO 86012009-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 :(得分:5)

>>> first, colon, rest = "commence:2009-11-19T19:55:00".partition(':')

>>> print (first, colon, rest)
('commence', ':', '2009-11-19T19:55:00')

答案 1 :(得分:5)

您可以在分割函数中放置最大分割参数

>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']

官方文件

  

S.split([sep [,maxsplit]]) - >字符串列表

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.

答案 2 :(得分:0)

看起来你需要.IndexOf(“:”),然后.Substring()?

答案 3 :(得分:0)

@P,不要做不必要的事。你正在做的事情不需要正则表达式。 Python有很好的字符串操作方法,你可以使用。你需要的只是split()和切片。这些是Python的基础知识。

>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']
>>>