Reputation: 1696
I need to find values inside this string:
10days25hours15minutes
I need get the numbers of days, hours and minutes, but the string can change, like this:
10d25h15m
Upvotes: 2
Views: 271
Reputation: 20424
You can use this regex:
(?<days>\d+)d\D*(?<hours>\d+)h\D*(?<minutes>\d+)m\D*
which matches
10days25hours15minutes
and 10d25h15m
. (and also others)
You may want to make it more accurate according to your needs.
Example code:
var match = System.Text.RegularExpressions.Regex.Match("10days25hours15minutes", @"(?<days>\d+)d\D*(?<hours>\d+)h\D*(?<minutes>\d+)m\D*", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (match.Success)
{
Console.WriteLine("Days: {0} Hours: {1} Minutes: {2}", match.Groups["days"], match.Groups["hours"], match.Groups["minutes"]);
}
Upvotes: 6
Reputation: 4908
Text.Split(new string[]
{"days", "hours", "minutes"},StringSplitOptions.RemoveEmptyEntries)
Or
Text.Split(new string[]{"d", "h", "m"},StringSplitOptions.RemoveEmptyEntries)
return your number ordinaly...
Upvotes: 0
Reputation: 18743
Regex.Match(str, @"(?<days>[0-9]+)(d|days)
(?<hours>[0-9]+)(h|hours)
(?<minutes>[0-9]+)(m|minutes)");
Then retrieve the values using match.Groups["days"].Value
, match.Groups["hours"].Value
, match.Groups["minutes"].Value
.
Upvotes: 1
Reputation: 217411
Assuming the input string consists of three decimal numbers each terminated by one or more non-digits, you can use the following regular expression:
var match = Regex.Match("10days25hours15minutes", @"(\d+)\D+(\d+)\D+(\d+)\D+");
var result = new TimeSpan(
days: int.Parse(match.Groups[1].Value),
hours: int.Parse(match.Groups[2].Value),
minutes: int.Parse(match.Groups[3].Value),
seconds: 0);
// result == {11.01:15:00}
Upvotes: 4