Reputation: 61
I have a 3 example strings (Timezones) and I want to fetch the (offset) of theirs.
GMT-05:00 Eastern Time(Toronto)
(GMT - 06:00) Central Time(US, Canada)
GMT-10:00 Hawaii - Aleutian Standard Time(Honolulu)
I want the above strings answers to be like :
-05:00
-06:00
-10:00
I have a regex [^0-9-:+]
which gives out the desired answers for the first and second example but for the third it results out as -10:00-
Please help me out building an required Regex to fetch the offset.
Upvotes: 3
Views: 153
Reputation: 626896
You may use
\bGMT\s*([-+]?)\s*(\d+:\d+)
See the regex demo. Details:
\bGMT
- a whole word GMT
\s*
- 0+ whitespaces([-+]?)
- Group 1: an optional -
or +
\s*
- 0+ whitespaces(\d+:\d+)
- 1+ digits, :
, 1+ digits.Then, you need to concat two groups to get the final value:
var strs = new String[] {"GMT-05:00 Eastern Time(Toronto)","(GMT - 06:00) Central Time(US, Canada)","GMT-10:00 Hawaii - Aleutian Standard Time(Honolulu)"};
foreach (var s in strs)
{
var result = Regex.Match(s, @"\bGMT\s*([-+]?)\s*(\d+:\d+)");
if (result.Success) {
Console.WriteLine($"Parsing '{s}'\nResult: {result.Groups[1].Value}{result.Groups[2].Value}");
}
}
See the C# demo, output:
Parsing 'GMT-05:00 Eastern Time(Toronto)'
Result: -05:00
Parsing '(GMT - 06:00) Central Time(US, Canada)'
Result: -06:00
Parsing 'GMT-10:00 Hawaii - Aleutian Standard Time(Honolulu)'
Result: -10:00
Upvotes: 2
Reputation: 3549
this regex will get you the expected result:
[\+|-]?\s*\d+:\d+
Also, it considers the possible whitespaces
Upvotes: -2