简体   繁体   English

C#正则表达式以匹配时间

[英]C# Regex to match time

I am trying to write a Regex to match the "time" ( hh:mm:ss ) for example 11:20:00 , 18:02:22 or 6:00:00 . 我想写一个正则表达式匹配“时间”( hh:mm:ss ),例如11:20:0018:02:226:00:00

I wrote the following but it does not work as expected. 我写了以下内容,但它没有按预期工作。 It matches when its the only thing in the string or if its the first value in the string. 当它是字符串中的唯一值或字符串中的第一个值时,它将匹配。 For example: 例如:

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 would yield 3 . returnedValue将产生3 But I want the whole time. 但是我一直都想。

If you only want the time and don't care about the rest of the line, it's ([0-1]?\\d|2[0-3]):(?:([0-5]?\\d))?:(?:([0-5]?\\d))? 如果您只想要时间而不在​​乎该行的其余部分,那就是([0-1]?\\d|2[0-3]):(?:([0-5]?\\d))?:(?:([0-5]?\\d))?

Try it here! 在这里尝试!

    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);

I use the following web site to lookup regexs, it may be useful for you... 我使用以下网站查找正则表达式,这可能对您有用...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM