Abhilash Gowda
Abhilash Gowda

Reputation: 61

Regex to fetch offset c#

I have a 3 example strings (Timezones) and I want to fetch the (offset) of theirs.

  1. GMT-05:00 Eastern Time(Toronto)
  2. (GMT - 06:00) Central Time(US, Canada)
  3. GMT-10:00 Hawaii - Aleutian Standard Time(Honolulu)

I want the above strings answers to be like :

  1. -05:00
  2. -06:00
  3. -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

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

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

Greedo
Greedo

Reputation: 3549

this regex will get you the expected result:

[\+|-]?\s*\d+:\d+

Also, it considers the possible whitespaces

Examples

Upvotes: -2

Justinas
Justinas

Reputation: 43479

Try regex [+-]?\s?\d{2}:\d{2} to match optional sign and then two decimal sequences

Example

Upvotes: 2

Related Questions