从特定字符串模式中提取部分

时间:2011-11-18 10:04:07

标签: c#

如何从下面的字符串中获取时间差,我希望得到它(-3.30)

[UTC - 3:30] Newfoundland Standard Time

以及如何从以下字符串中获取null

[UTC] Western European Time, Greenwich Mean Time

我想在下面的字符串中获得+3.30

[UTC + 3:30] Iran Standard Time

4 个答案:

答案 0 :(得分:5)

正则表达式:

\[UTC([\s-+0-9:]*)\]

第一组是- 3:30。 (带空格)

var regex = new Regex(@"\[UTC([\s-+0-9:]*)\]");
var match = regex.Match(inputString);

string timediff;
if(match.Groups.Count > 0)
    timediff = match.Groups[1].Value.Replace(" ", String.Empty); // if you don't want those spaces
else
    // no timediff here

答案 1 :(得分:2)

您可以使用以下内容提取相关部分:

Assert(input.StartsWith("[UTC",StringComparison.InvariantCultureIgnoreCase));
string s=input.Substring(4,input.IndexOf(']')-4).Replace(" ","");

要在几分钟内从此字符串中获取偏移量:

if(s=="")s="0:00";
var parts=s.Split(':');
int hourPart=int.Parse(parts[0], CultureInfo.InvariantCulture);
int minutePart=int.Parse(parts[1], CultureInfo.InvariantCulture);
int totalMinutes= hourPart*60+minutePart*Math.Sign(hourPart);
return totalMinutes;

答案 2 :(得分:2)

由于您只对这些数字感兴趣,您也可以使用它。

  String a = "[UTC - 3:30] Newfoundland Standard Time";
  String b = "[UTC] Western European Time, Greenwich Mean Time";
  String c = "[UTC + 3:30] Iran Standard Time";

  Regex match = new Regex(@"(\+|\-) [0-9]?[0-9]:[0-9]{2}");

  var matches = match.Match(a); // - 3:30
  matches = match.Match(b); // Nothing
  matches = match.Match(c); // + 3:30

还支持+10小时偏移。

答案 3 :(得分:0)

试试这个:

    public string GetDiff(string src)
    {
        int index = src.IndexOf(' ');
        int lastindex = src.IndexOf(']');
        if (index < 0 || index > lastindex) return null;
        else return src.Substring(index + 1, lastindex - index -1 )
                       .Replace(" ", "").Replace(":", ".");
    }