【问题标题】:Named Groups in Regular Expression正则表达式中的命名组
【发布时间】:2009-07-07 10:31:37
【问题描述】:

我想解析输入字符串并从中提取值。我的输入字符串可能有周、天、小时或分钟。

所以,输入字符串可能是

  • 1 周 5 天 2 小时 1 分钟
  • 或 3 分钟
  • 或5天1分钟
  • 或 2 小时等

我想使用正则表达式提取值。

如何在 .Net 中实现这一点?

【问题讨论】:

  • 它们会一直井井有条吗?

标签: .net regex


【解决方案1】:

我认为使用正则表达式会有点矫枉过正。如果我是你,我只会标记字符串,将其转换为小写,然后在不同的单词之间切换。这是处理已修复已知子字符串的情况的更好方法。

【讨论】:

  • 来自铁杆正则表达式用户的+1,这对正则表达式来说不是一个很好的用途,因为它将是多次传递正则表达式。如果您尝试容忍替代拼写和其他逻辑,将很难维护。如果你真的有兴趣,有一个用 ruby​​ 编写的库,叫做 chronos,它专门做这种输入,它的来源可能很有价值,看看他们是如何做到的。
【解决方案2】:

只要项目按顺序排列,以下正则表达式匹配单数或复数(例如天或天)。

//Set the input and pattern
string sInput = "1 Weeks 5 Days 2 Hours 1 Minutes";
string sPattern = "^\s*(?:(?<weeks>\d+)\s*(?:weeks|week))?\s*(?:(?<days>\d+)\s*(?:days|day))?\s*(?:(?<hours>\d+)\s*(?:hours|hour))?\s*(?:(?<minutes>\d+)\s*(?:minutes|minute))?";

//Run the match
Match oMatch = Regex.Match(sInput, sPattern, RegexOptions.IgnoreCase);

//Get the values
int iWeeks = int.Parse(oMatch.Groups["weeks"].Value);
int iDays = int.Parse(oMatch.Groups["days"].Value);
int iHours = int.Parse(oMatch.Groups["hours"].Value);
int iMinutes = int.Parse(oMatch.Groups["minutes"].Value);

【讨论】:

    【解决方案3】:

    Regex 中的捕获组用括号括起来(例如"(\d+ Week)")。

    使用问号和名称"(?&lt;week&gt;\d+ Week)" 完成命名捕获组。

    然后返回如下,m.Groups("week").Value

    完整的正则表达式(未经测试)可能如下所示:

      (?<weeks>\d+ weeks?)\s*(?<days>\d+ days?)\s*(?<hours>\d+ hours?)\s*(?<minutes>\d+ minutes?)
    

    【讨论】:

      【解决方案4】:

      这是一个粗略的示例,说明如何解析文本以获取各种值。

      Dim inputString As String = "1 Week 5 Days 2 Hours 1 Minutes"
      Dim pattern As String = "(?<Week>\d+)\s*week\s*(?<Days>\d+)\s*days\s*(?<Hours>\d+)\s*hours"
      
      Dim m As Match = Regex.Match(inputString, pattern, RegexOptions.Compiled Or RegexOptions.Singleline Or RegexOptions.IgnoreCase)
      
      If m.Success Then
        Dim hours As String = m.Groups("Hours")
         etc...
      End If
      

      【讨论】:

        猜你喜欢
        • 2014-11-11
        • 1970-01-01
        • 2010-09-29
        • 2018-01-29
        • 2020-05-23
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多