Find and extract a number from a string

前端 未结 29 3175
温柔的废话
温柔的废话 2020-11-22 03:19

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = \"1 test\"
string test1 =         


        
29条回答
  •  一整个雨季
    2020-11-22 03:43

    if the number has a decimal points, you can use below

    using System;
    using System.Text.RegularExpressions;
    
    namespace Rextester
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                //Your code goes here
                Console.WriteLine(Regex.Match("anything 876.8 anything", @"\d+\.*\d*").Value);
                Console.WriteLine(Regex.Match("anything 876 anything", @"\d+\.*\d*").Value);
                Console.WriteLine(Regex.Match("$876435", @"\d+\.*\d*").Value);
                Console.WriteLine(Regex.Match("$876.435", @"\d+\.*\d*").Value);
            }
        }
    }
    

    results :

    "anything 876.8 anything" ==> 876.8

    "anything 876 anything" ==> 876

    "$876435" ==> 876435

    "$876.435" ==> 876.435

    Sample : https://dotnetfiddle.net/IrtqVt

提交回复
热议问题