【问题标题】:Get decimal value from string using regex C#使用正则表达式 C# 从字符串中获取十进制值
【发布时间】:2018-11-01 05:11:26
【问题描述】:

我想提取输入字符串的十进制值

Total (pre tax) 93.78 EUR

我试过了

Regex.Replace(string input, "[^0-9]+", string.Empty)

但它只提取了9370,其中预期的结果是93.78

请帮助我获取十进制值的模式。

【问题讨论】:

  • 试试 [0-9]*\.?[0-9]+
  • 试试Regex.Replace(string input, "[^\d\.]", string.Empty),如果小数可能是负值,试试Regex.Replace(string input, "[^\d\.-]", string.Empty)
  • 正如 Dmitry Bychenko 在他的回答中指出的那样......为什么你要删除你不需要的所有东西,而不是简单地匹配你确实需要的部分?

标签: c# regex


【解决方案1】:

我建议匹配而不是替换:让我们提取感兴趣的值,而不是删除所有其他角色。

string result = Regex.Match(
     "Total (pre tax) 93.78 EUR", 
    @"[0-9]+(\.[0-9]+)?")
  .Value;

【讨论】:

    【解决方案2】:

    您当前正在替换所有不是数字的内容 - 包括 .

    我建议您使用可选的“点后跟更多数字”来捕获数字组。这样,您也可以从文本中捕获多个值 - 或者根据您拥有的任何标准在需要时拒绝它。这是一个例子:

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
        public static void Main()        
        {
            string text = "I start with 5 and take away 2.52 to get 2.48 as a result";
            Regex regex = new Regex(@"\d+(\.\d+)?");
            var matches = regex.Matches(text);
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }
        }
    }
    

    输出:

    5
    2.52
    2.48
    

    您可以使用MatchCollection.Count 来确定有多少匹配项 - 我们不知道您的上下文,但您可能希望根据没有匹配项、只有一个匹配项还是多个匹配项采取不同的操作匹配。

    【讨论】:

      【解决方案3】:

      如果您将'.' 添加到您希望保留的字符列表中,即[^0-9.],您可以使用您的方法作为快速破解。但是,这还不够健壮,因为它会保留其他数字,例如

      Total (inclusive of 20% VAT) 93.78 EUR
      

      会产生2093.78,这不是您要找的。​​p>

      更好的方法是使用特定于价格的正则表达式,例如

      @"(\d+[.,]\d\d) EUR"
      

      将匹配带有两位小数的数字,当它后跟EUR

      【讨论】:

        【解决方案4】:

        对于整数或浮点数:

        string result = Regex.Match(input,@"[0-9]+(\.[0-9]+)?").Value;
        

        仅适用于浮动:

        string result = Regex.Match(input,@"[0-9]+\.[0-9]+").Value;
        

        【讨论】:

          【解决方案5】:

          Regex.Split() 会从输入字符串中提取所有浮点值并存入string[],就像string.Split函数一样简单

          你可以试试这个:

          string stringInput = "Total (pre tax) 93.78 EUR";
          string[] splitValue = Regex.Split (stringInput , @"[^0-9\.]+");
          foreach(string item in splitValue)
          {
              //Here you can convert it to decimal
              Console.WriteLine(item);
          }
          

          输出:

          93.78
          

          DotnetFiddler

          【讨论】:

            【解决方案6】:
            string input = "Java JDK 12.0.1";
            var result = Regex.Matches(input, @"[0-9]+(\.[0-9]\.[0-9]+)?");
            

            结果:1​​2.0.1

            【讨论】:

              猜你喜欢
              • 2014-04-24
              • 1970-01-01
              • 1970-01-01
              • 2021-09-19
              • 2016-08-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多