Search code examples
c#regexreplacecalculatordynamic-expresso

Replace numbers in string to numbers + "f"


I want to make tiny calculator that if you write for example 2/3 and you have got 0.6666667. I use DynamicExpresso.Core library but I need to write 2f/3f to have 0.6666667 (if I write 2/3 I get 0). I think I should use somethink like forCounting = Regex.Replace(forCounting, Regex.Match(forCounting, @"\d+").Value, Regex.Match(forCounting, @"\d+").Value + "f"); but it adds f after only first number. Do you have any ideas?


Solution

  • Use

    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);
        }
    }
    

    See C# proof.

    Results: Text: 2f/3f, 1.9f