简体   繁体   中英

Regex extract time from GMT string

I have strings such as

(GMT -4:00)Puerto Rico
(GMT -3:30)Newfoundland
(GMT -3:00)Asuncion
(GMT +2:00)Athens

How can I extraxt the time from those string? This was my poor shot: \\([0-9](.*?)\\) Result should look like this: -4:00, -3:30, -3:00...

I am very bad at this.

You may use a mere

[-+]\d+:\d+

See the regex demo

Details :

  • [-+] - matches - or +
  • \\d+ - 1 or more digits
  • : - a colon
  • \\d+ - 1 or more digits.

在此处输入图片说明

C#:

var results = Regex.Matches(s, @"[-+]\d+:\d+", RegexOptions.ECMAScript)
    .Cast<Match>()
    .Select(m => m.Value)
    .ToList();

A possible alternative non-regex solution to process each separate input:

var s = "(GMT -4:00)Puerto Rico";
var res = s.Split(new[] {" ", ")"}, StringSplitOptions.RemoveEmptyEntries)
    .Skip(1)
    .FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM