how get integer only and remove all string in C#

input = Regex.Replace(input, "[^0-9]+", string.Empty);

There is four different ways to do it (well probably more but I've selected these).

#1: Regex from Bala R

string output = Regex.Replace(input, "[^0-9]+", string.Empty);

#2: Regex from Donut and agent-j

string output = Regex.Match(input, @"\d+").Value;

#3: Linq

string output = new string(input.ToCharArray().Where(c => char.IsDigit(c)).ToArray());

#4: Substring, for this to work the dash has to be in the string between the digits and the text.

string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "");

With these inputs:

string input1 = "01 - ABCDEFG";
string input2 = "01 - ABCDEFG123";

For 1 and 2 the results would be:

output1 = "01";
output2 = "01123";

For 3 and 4 the results would be:

output1 = "01";
output2 = "01";

If the expected result is to get all the digits in the string, use #1 or #2, but if the expected result is to only get the digits before the dash, use #3 or #4.

With string as short as this #1 and #2 are about equal in speed and likewise for #3 and #4, but if there is a lot of iterations or the strings are four times longer or more #2 is faster than #1 and #4 is faster than #3.

Note: If the parentheses is included in the strings #4 has to be modifyed to this, but that wont make it much slower:

string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "").Replace("(", "");

try this:

Convert.ToInt32(string.Join(null, System.Text.RegularExpressions.Regex.Split(s, "[^\\d]")))

it returns integer value 1.

Tags:

C#

String

Integer