Find and extract a number from a string

前端 未结 29 3405
温柔的废话
温柔的废话 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 03:39

    \d+ is the regex for an integer number. So

    //System.Text.RegularExpressions.Regex
    resultString = Regex.Match(subjectString, @"\d+").Value;
    

    returns a string containing the first occurrence of a number in subjectString.

    Int32.Parse(resultString) will then give you the number.

提交回复
热议问题