Find and extract a number from a string

前端 未结 29 2788
温柔的废话
温柔的废话 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

    0 讨论(0)
  • 2020-11-22 03:45
      string verificationCode ="dmdsnjds5344gfgk65585";
                string code = "";
                Regex r1 = new Regex("\\d+");
              Match m1 = r1.Match(verificationCode);
               while (m1.Success)
                {
                    code += m1.Value;
                    m1 = m1.NextMatch();
                }
    
    0 讨论(0)
  • 2020-11-22 03:49

    Here's a Linq version:

    string s = "123iuow45ss";
    var getNumbers = (from t in s
                      where char.IsDigit(t)
                      select t).ToArray();
    Console.WriteLine(new string(getNumbers));
    
    0 讨论(0)
  • 2020-11-22 03:50

    Here's how I cleanse phone numbers to get the digits only:

    string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
    
    0 讨论(0)
  • 2020-11-22 03:50
    static string GetdigitFromString(string str)
        {
            char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            char[] inputArray = str.ToCharArray();
            string ext = string.Empty;
            foreach (char item in inputArray)
            {
                if (refArray.Contains(item))
                {
                    ext += item.ToString();
                }
            }
            return ext;
        }
    
    0 讨论(0)
  • 2020-11-22 03:51

    use regular expression ...

    Regex re = new Regex(@"\d+");
    Match m = re.Match("test 66");
    
    if (m.Success)
    {
        Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
    }
    else
    {
        Console.WriteLine("You didn't enter a string containing a number!");
    }
    
    0 讨论(0)
提交回复
热议问题