Walters
Walters

Reputation: 131

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 .

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. But I want the whole time.

Upvotes: 0

Views: 1877

Answers (2)

Nick Reed
Nick Reed

Reputation: 5059

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

Try it here!

Upvotes: 3

quaabaam
quaabaam

Reputation: 1972

    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

Another nice information source, https://www.regular-expressions.info/tutorial.html

Upvotes: 1

Related Questions