this note
this note

Reputation: 213

Regex matching "time" values in a string

I am trying to match several patterns in a string with a regular expression add a delimiter and add them to a string or list. Description is the string i'm trying to test.

Here's the text I'm trying to match "01:00 02:00 03:00" previous attempts I was able to match "01:00", but I want to match all 3 cases.

var pattern = @"^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$";
var ReturnTime = "";
foreach(Match match in Regex.Matches(Description, pattern)) {
  ReturnTime += match.Value + ";";
}

Upvotes: 2

Views: 1093

Answers (2)

Diosjenin
Diosjenin

Reputation: 743

(0[0-9]|1[1-2]):[0-5][0-9](?=[^0-9])

will match standard time (Link), while

([0-1][0-9]|2[0-3]):[0-5][0-9](?=[^0-9])

will match military time (Link).

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

You have to remove your anchors ^ and $ for that purpose:

var pattern = @"(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)";
               ^                                                ^

See DEMO

Upvotes: 4

Related Questions