Finding all numbers in a string

前端 未结 2 1671
醉话见心
醉话见心 2020-12-10 20:52

Part of my app has an area where users enter text into a textBox control. They will be entering both text AND numbers into the textBox. When the user pushes a button, the te

相关标签:
2条回答
  • 2020-12-10 21:11

    You can use a regular expression that matches the numbers, and use the Regex.Replace method. I'm not sure what you include in the term "numbers", but this will replace all non-negative integers, like for example 42 and 123456:

    str = Regex.Replace(
      str,
      @"\d+",
      m => (Double.Parse(m.Groups[0].Value) * 1.14).ToString()
    );
    

    If you need some other definition of "numbers", for example scientific notation, you need a more elaboarete regular expression, but the principle is the same.

    0 讨论(0)
  • 2020-12-10 21:18

    Freely adopted from the sample here

    Beware of your regional options (since you're parsing and serializing floating point numbers)

    using System;
    using System.Text.RegularExpressions;
    
    class MyClass
    {
       static void Main(string[] args)
       {
          var input = "a 1.4 b 10";
    
          Regex r = new Regex(@"[+-]?\d[\d\.]*"); // can be improved
    
          Console.WriteLine(input);
          Console.WriteLine(r.Replace(input, new MatchEvaluator(ReplaceCC)));
       }
    
       public static string ReplaceCC(Match m)
       {
           return (Double.Parse(m.Value) * 1.14).ToString();
       }
    }
    
    [mono] ~ @ mono ./t.exe
    a 1.4 b 10
    a 1.596 b 11.4
    
    0 讨论(0)
提交回复
热议问题