Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and extract a number from a string

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 = " 1 test" string test2 = "test 99" 

How can I do this?

like image 795
van Avatar asked Jan 19 '11 10:01

van


1 Answers

\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.

like image 84
Tim Pietzcker Avatar answered Sep 21 '22 04:09

Tim Pietzcker