【问题标题】:Trying to pull out dates and version numbers from script comments, using regex尝试使用正则表达式从脚本注释中提取日期和版本号
【发布时间】:2014-08-28 02:11:16
【问题描述】:

我正在尝试从脚本文件中的 cmets 中提取信息。将文件作为输入后,我想运行一个搜索,它会以以下形式提取信息:

“版本:#.#”

“创建日期:##/##/####”

等等

我的一个问题是版本号和日期不会总是采用这种格式。有时,它们可能看起来像:

“版本号”

“创建日期:##/####”

cmets 通常充满了大量的“#”,所以我的正则表达式到目前为止的样子是: [\s\S]*(版本:?\s\d.?\d|创建日期:?\d+/\d+/\d{2,4}?)

我试图让它更健壮,以便处理不同的场景(就像我上面写的那样),我想要解决的主要问题是:它只是拉无论是日期还是版本,我都知道这是由于管道 (|) 造成的,而且因为我不太了解正则表达式,所以我不确定如何获取这两条信息。

感谢您的帮助!

【问题讨论】:

  • 那是因为管道| 操作符的意思是This OR That

标签: python regex input


【解决方案1】:

你可以使用这个正则表达式,

Version:?\s*\S*|Date Created:?\s*\S*

【讨论】:

    【解决方案2】:
    1. 我认为将您的正则表达式拆分为多个正则表达式更容易(即,一个用于版本,另一个用于日期)
    2. 您应该使用锚点^regex$ 以便找到有问题的整行。这通常会使您的正则表达式更快,但绝对更具体。

    例子:

    import re
    
    txt='''\
    # Version: #.#"
    
    # Date Created: ##/##/####"
    
    etc.
    
    One of my problems is that the version numbers and dates wont always be in that format. Sometimes, they may look like:
    
    # Version #"
    
    # Date Created: ##/####'''
    
    print 'versions found:', re.findall(r'^\s*#+\s*Version:?\s*(.*)$', txt, re.M)    
    print 'dates found:', re.findall(r'^\s*#+\s* Date Created:?\s*(.*)$', txt, re.M)
    

    打印:

    versions found: ['#.#"', '#"']
    dates found: ['##/##/####"', '##/####']
    

    【讨论】:

    • 非常感谢!我想拆分正则表达式是最好的方法,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2013-02-24
    • 2015-01-12
    相关资源
    最近更新 更多