简体   繁体   English

正则表达式从GMT字符串中提取时间

[英]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... 这是我可怜的照片: \\([0-9](.*?)\\)结果应该像这样: -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 \\d+ -1个或更多数字
  • : - a colon : -冒号
  • \\d+ - 1 or more digits. \\d+ -1个或多个数字。

在此处输入图片说明

C#: 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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