【问题标题】:Regex to Split 1st Colon正则表达式拆分第一个冒号
【发布时间】:2009-11-20 13:56:31
【问题描述】:

我在 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)有可能,是的……

【问题讨论】:

  • 冒号前部分的可能值是多少?只有“开始”?

标签: python regex


【解决方案1】:
>>> first, colon, rest = "commence:2009-11-19T19:55:00".partition(':')

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

【讨论】:

  • 太完美了。我不知道partition 函数!
【解决方案2】:

你可以把最大分割参数放在分割函数中

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 我认为语言是 Python。
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2013-01-26
      相关资源
      最近更新 更多