Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从特定的字符串模式中提取零件_C# - Fatal编程技术网

C# 从特定的字符串模式中提取零件

C# 从特定的字符串模式中提取零件,c#,C#,如何从下面的字符串中获取时间差,我想使用(-3.30)获取时间差 以及如何从下面的字符串中获取null [UTC] Western European Time, Greenwich Mean Time [UTC + 3:30] Iran Standard Time 我想在下面的字符串中得到+3.30 [UTC] Western European Time, Greenwich Mean Time [UTC + 3:30] Iran Standard Time 您可以使用以下方法提取相关部

如何从下面的字符串中获取时间差,我想使用(-3.30)获取时间差

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

[UTC] Western European Time, Greenwich Mean Time
[UTC + 3:30] Iran Standard Time
我想在下面的字符串中得到+3.30

[UTC] Western European Time, Greenwich Mean Time
[UTC + 3:30] Iran Standard Time

您可以使用以下方法提取相关部分:

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;
正则表达式:

\[UTC([\s-+0-9:]*)\]
第一组是
-3:30
。(带空格)

试试这个:

    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(":", ".");
    }
公共字符串GetDiff(字符串src)
{
int index=src.IndexOf(“”);
int lastindex=src.IndexOf(']');
if(index<0 | | index>lastindex)返回null;
else返回src.Substring(index+1,lastindex-index-1)
.Replace(“,”).Replace(“:”,”);
}

因为您只对数字感兴趣,所以也可以使用此选项

  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小时的偏移量。

您需要解析字符串,以获取将在-。这完全取决于可能要通过的字符串,如果它们都要始终以[UTC-…开头,则将字符串除以“[UTC-”和以下“]”。我还将使正则表达式更加严格,检查您正在查看的部分是否以
[UTC
开始,以
结束
@CodeInChaos:是的,也许吧。我觉得正则表达式很棒,但有这么简单的情况是不必要的……我错了吗?不管怎样,我看到你们是另一个受害者;)嘿,伙计们,我喜欢你们的解决方案,所以我要帮你们:)