【问题标题】:Regex take numbers from string c#正则表达式从字符串 c# 中获取数字
【发布时间】:2018-10-11 15:02:13
【问题描述】:

我想将该类型的字符串坐标拆分为 -54°32'17,420" 以列出每个数字,例如 [54,32,17,420]。我正在使用

var longitudeSplitted = Regex.Split(longitutdeString, @"\D+")
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Distinct()
    .Select(int.Parse)
    .ToList();

它一般都可以,但是当我有这样的坐标时问题就出现了

-11°42'42,420" 在这种情况下,我收到的列表只有 3 个数字 [11,42,420]。 问题出在哪里?我真的不明白这种行为。

【问题讨论】:

  • 删除Distinct
  • 天啊,当然!谢谢你:)
  • "-11°42'42,420\"".Split("°',.\"".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 然后你可以保留 +/-(还包括使用句点作为小数分隔符的文化的句点)
  • 来自 goscamp:正如@juharr 所写,不需要区分:)
  • @PanagiotisKanavos 我不明白为什么这不是这个问题的答案。当然,它缺少一点细节,不应该写成评论,但这实际上是这个问题的答案。移除对Distinct()的调用。

标签: c# regex string list linq


【解决方案1】:

这行得通:

   var numRegex = new Regex(@"[\+\-0-9]+");
   var numMatches = numRegex.Matches("-11°42'43,440");

我在字符串中保留了 +/-(以区分东与西),并将数字更改为更独特的数字。您最终会在 numMatches.Items 中得到 4 个字符串,每个字符串都可以解析为一个 int。它也适用于“-11°42'42,420”,但我也想用唯一的数字来测试它

【讨论】:

    【解决方案2】:

    这是一个你可以使用的辅助方法

    private static List<int> ExtratctCordinates(string input)
    {
        List<int> retObj = new List<int>();
        if(!string.IsNullOrEmpty(input))
        {
            int tempHolder;
            // Use below foreach with simple regex if you want sign insensetive data
            //foreach (Match match in new Regex(@"[\d]+").Matches(input))
    
            foreach (Match match in new Regex(@"[0-9\+\-]+").Matches(input))
            {
                if (int.TryParse(match.Value, out tempHolder))
                {
                    retObj.Add(tempHolder);
                }
            }
        }
        return retObj;          
    }
    

    这里是示例调用

    List<int> op = ExtratctCordinates("-54°32'17,420\"");
    

    【讨论】:

      【解决方案3】:

      正如问题的 cmets 中所提到的,问题在于对 Distinct() 的调用。

      我给出的示例"-11°42'42,420" 包含两次数字42,因此其中一个因调用Distinct() 而被删除。

      固定的表达式是这样的:

      var longitudeSplitted = Regex.Split(longitutdeString, @"\D+")
          .Where(s => !string.IsNullOrWhiteSpace(s))
          .Select(int.Parse)
          .ToList();
      

      此外,我原来的正则表达式 @"\D+" 未能包含负数符号。我不得不重写为使用 .Matches(...) 而不是 .Split(...) 来包含符号。

      因此正确的表达是这样的:

      var longitudeSplitted = Regex.Matches(longitutdeString, @"[-+]?\d+").OfType<Match>()
          .Select(match => match.Value)
          .Where(s => !string.IsNullOrWhiteSpace(s))
          .Select(int.Parse)
          .ToList();
      

      【讨论】:

      • 这真的是评论,而不是答案。多一点代表,you will be able to post comments。目前我已经为你添加了评论,我标记了这篇文章以供删除。
      猜你喜欢
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2013-07-31
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多