Find and extract a number from a string

前端 未结 29 2753
温柔的废话
温柔的废话 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: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!");
    }
    

提交回复
热议问题