Find and extract a number from a string

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

    Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

    // Pull out only the numbers from the string using LINQ
    
    var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
    
    var numericVal = Int32.Parse(numbersFromString);
    

提交回复
热议问题