【问题标题】:Replace numbers in string to numbers + "f"将字符串中的数字替换为数字+“f”
【发布时间】:2021-03-11 22:04:03
【问题描述】:

我想制作一个微型计算器,如果你写例如 2/3 并且你有 0.6666667。我使用 DynamicExpresso.Core 库,但我需要编写 2f/3f 以获得 0.6666667(如果我编写 2/3 我得到 0)。我想我应该使用像forCounting = Regex.Replace(forCounting, Regex.Match(forCounting, @"\d+").Value, Regex.Match(forCounting, @"\d+").Value + "f"); 这样的想法,但它只在第一个数字之后添加 f。你有什么想法吗?

【问题讨论】:

    标签: c# regex replace calculator dynamic-expresso


    【解决方案1】:

    使用

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
        public static void Main()
        {
            string pattern = @"\d+(?:\.\d+)?";
            string substitution = "$0f";
            string input = "Text: 2/3, 1.9";
            string result = Regex.Replace(input, pattern, substitution);
            Console.WriteLine(result);
        }
    }
    

    C# proof

    结果Text: 2f/3f, 1.9f

    【讨论】:

      【解决方案2】:

      从 DynamicExpresso 2.6.0 开始,可以设置默认数字类型。
      例如,您可以要求它将所有数字视为双精度数,并得到您期望的结果:

      var target = new Interpreter();
      target.SetDefaultNumberType(DefaultNumberType.Double);
      
      var dbl = target.Eval<double>("2/3");
      Console.WriteLine(dbl); // 0.6666666666666666
      

      【讨论】:

        【解决方案3】:

        好代码:

        forCounting= Regex.Replace(forCounting, @"([0-9.]+)", @"$0f");
        

        【讨论】:

        • 这不好,([0-9.]+) 也匹配 ........。查看我的更新。
        猜你喜欢
        • 2017-11-29
        • 2021-11-02
        • 2013-11-08
        • 1970-01-01
        • 2022-11-12
        • 2022-11-12
        • 2021-12-20
        • 2018-04-30
        相关资源
        最近更新 更多