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 =
Here is another Linq
approach which extracts the first number out of a string.
string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
.SkipWhile(x => !char.IsDigit(x))
.TakeWhile(x => char.IsDigit(x))
.ToArray()), out result);
Examples:
string input = "123 foo 456"; // 123
string input = "foo 456"; // 456
string input = "123 foo"; // 123
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);
\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.
You can also try this
string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
Just use a RegEx to match the string, then convert:
Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
int val;
if(int.TryParse(match.Value,out val))
{
//val is set
}
}