【问题标题】:C# Regex to match timeC#正则表达式匹配时间
【发布时间】:2019-07-26 19:50:55
【问题描述】:

我正在尝试编写一个正则表达式来匹配“时间”(hh:mm:ss),例如 11:20:0018:02:226:00:00

我写了以下内容,但它没有按预期工作。 当它是字符串中唯一的东西或者它是字符串中的第一个值时,它匹配。 例如:

string timepattern = @"^([0-1]?\d|2[0-3])(?::([0-5]?\d))?(?::([0-5]?\d))?";
string value = "30.Jul.2019 This the line I want to match 15:04:09"
var returnedValue = Regex.Match(line, timepattern);

returnedValue 将产生3。但我想要整个时间。

【问题讨论】:

标签: c# regex


【解决方案1】:

如果你只想要时间而不关心线路的其余部分,那就是([0-1]?\d|2[0-3]):(?:([0-5]?\d))?:(?:([0-5]?\d))?

Try it here!

【讨论】:

    【解决方案2】:
        string timepattern = @"(?:2[0-3]|[01]?[0-9])[:.][0-5]?[0-9][:.][0-5]?[0-9]";
        string value = "30.Jul.2019 This the line I want to match 15:04:09";
        var returnedValue = Regex.Match(value, timepattern);
    

    我使用以下网站查找正则表达式,它可能对您有用...

    http://regexlib.com/Search.aspx?k=time+hh%3amm%3ass&c=-1&m=-1&ps=20

    另一个不错的信息源, https://www.regular-expressions.info/tutorial.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多