gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:42:26 24 4
gpt4 key购买 nike

我有这样的字符串

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

如何从这些字符串中提取时间?这是我糟糕的一击:\([0-9](.*?)\)结果应如下所示:-4:00, -3:30, -3:00...

我很不擅长这个。

最佳答案

你可以仅仅使用

[-+]\d+:\d+

参见 regex demo

详细信息:

  • [-+] - 匹配 -+
  • \d+ - 一位或多位数字
  • : - 冒号
  • \d+ - 1 个或多个数字。

enter image description here

C#:

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

一个可能的选择 non-regex solution处理每个单独的输入:

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

关于c# - 正则表达式从 GMT 字符串中提取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42541424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com