2009-11-20 32 views
2

我在ISO 86012009-11-19T19:55:00)中有一段时间,它也与名称commence配对。我试图将其解析为两个。我目前最多到这里:正则表达式到第1个冒号

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'] 

我会如何做这在原创​​?另外,您是否推荐任何您发现有用的正则表达式链接或书籍,因为我可以看到自己在未来需要它!

编辑:

为了澄清...我需要一个正则表达式,只会在解析的:第一个实例,这可能吗?冒号之前的文本(commence)有可能,是的...

+0

冒号前部分的可能值是多少?只有“开始”? – 2009-11-20 13:58:33

回答

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

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

这很完美。我不知道'分区'功能! – Federer 2009-11-20 14:23:25

+0

也称为split() – 2011-08-18 18:57:33

0

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

+0

我认为语言是Python。 – ghostdog74 2009-11-20 14:21:05

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. 
0

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

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