使用RegEx在.NET命令行工具中解析日期

时间:2013-01-05 22:44:03

标签: .net regex vb.net

在我正在使用的vb.net命令行工具中有一个名为period P的命令: 我想以下列格式指定日期

P:2009                       'translate this to 01.01.2009 to 31.12.2009
P:2008 To 2010               'translate this to 01.01.2008 to 31.12.2010
P:01.01.2012 To 22.11.2013   'stays the same

在我得到P之后的文本之后:我想使用正则表达式验证它并添加缺少的部分,因为我将在sql命令中使用它。

任何adivce?

4 个答案:

答案 0 :(得分:3)

这里不需要正则表达式;只是String.Split()围绕“To”,然后String.Split围绕“。”在结果上。根据结果​​数组的大小,您知道是否仅从年份或三个组件创建结果文本。

答案 1 :(得分:1)

我知道,您并不是在寻找Python解决方案,但也许这可以让您了解如何使用您的语言来实现:

In [1]: import re

In [2]: re.sub(r'P:(\d{4})', '01.01.\g<1> to 31.12.\g<1>', 'P:2009')
Out[2]: '01.01.2009 to 31.12.2009'

In [3]: re.sub(r'P:(\d{4}) To (\d{4})', '01.01.\g<1> to 31.12.\g<2>', 'P:2008 To 2010')
Out[3]: '01.01.2008 to 31.12.2010'

没有正则表达式的解决方案可能如下所示:

In [4]: def create_date(s):
  ....:     if s.startswith('P:'):
  ....:         years = s[2:].split(' To ')
  ....:         if len(years) == 1:
  ....:             return '01.01.' + years[0] + ' to 31.12.' + years[0]
  ....:         elif len(years) == 2:
  ....:             return '01.01.' + years[0] + ' to 31.12.' + years[1]         

In [5]: create_date('P:2008')
Out[5]: '01.01.2008 to 31.12.2008'

In [6]: create_date('P:2008 To 2010')
Out[6]: '01.01.2008 to 31.12.2010'

答案 2 :(得分:1)

这是C#代码,可以直接转换为vb.net:)

     string input = "P:2008 To 2010";
     string result = Regex.Replace(input, "^P:([0-9]{4})$", "P:01.01.$1");
     if (input == result)
     {
        result = Regex.Replace(input, "^P:([0-9]{4}) To ([0-9]{4})$", "P:01.01.$1 to 01.01.$2");
     }

答案 3 :(得分:1)

因为您不打算将日期字符串传递给SQL(你是吗?),所以你也可以解析日期以确保有效性:

Imports System.Globalization

Module Module1

    ' Take a string of year or year and month or year and month and day and
    ' convert it to a DateTime, defaulting to month=1 or day=1 if they are missing
    ' Throw an exception if this is not possible.
    Function MakeExplicitDate(s As String) As DateTime
        Dim cul = New CultureInfo("en-GB")
        Dim dt As DateTime

        If Not DateTime.TryParse(s, cul, Nothing, dt) Then
            s &= "-01"
            If Not DateTime.TryParse(s, cul, Nothing, dt) Then
                s &= "-01"
                If Not DateTime.TryParse(s, cul, Nothing, dt) Then
                    Throw New Exception("Could not parse date.")
                End If
            End If
        End If

        Return dt

    End Function

    Sub Main()

        Dim s = "P:2009 to 2011.02.13"

        If s.StartsWith("P:") Then

            s = s.Substring(2, Math.Max(0, s.Length - 2))
            Dim dates = s.ToLowerInvariant.Split({"to"}, StringSplitOptions.RemoveEmptyEntries)

            If dates.Count > 2 Then
                Throw New Exception("Too many dates supplied.")
            End If

            Dim datesToUse As New List(Of DateTime)

            For i = 0 To dates.Count - 1
                datesToUse.Add(MakeExplicitDate(dates(i)))
            Next

            For Each dtu In datesToUse
                Console.WriteLine(dtu.ToString("yyyy-MM-dd"))
            Next

        End If

        Console.ReadLine()

    End Sub

End Module
相关问题