16

How can I remove the strings and get only integers?

I have a string ( 01 - ABCDEFG )

i need to get (01) only

Roman
  • 19,581
  • 6
  • 68
  • 84
ghie
  • 567
  • 4
  • 11
  • 26

10 Answers10

37
input = Regex.Replace(input, "[^0-9]+", string.Empty);
Bala R
  • 107,317
  • 23
  • 199
  • 210
12

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("(", "");
Jens Granlund
  • 4,950
  • 1
  • 31
  • 31
4

try this:

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

it returns integer value 1.

1

Get All Numbers from string

string str = "01567438absdg34590";
            string result = "";

             result = Regex.Replace(str, @"[^\d]", "");

            Console.WriteLine(result);
            Console.Read();

Output: 0156743834590

Mizanur Rahman
  • 272
  • 2
  • 11
1
string snum = System.Text.RegularExpression.Regex.Match(s, "\d+").Value;
int num;
if (!int.TryParse(snum, out num))
  throw new Exception();
agent-j
  • 27,335
  • 5
  • 52
  • 79
1

You should use Regular Expressions -- they're a pretty powerful way to match strings of text against certain patterns, and this is a great scenario in which to use them.

The pattern "\d+" will match a sequence of 1 or more digits. A simple method that uses this pattern to extract all numbers from a string is as follows:

public static List<int> ExtractInts(string input)
{
   return Regex.Matches(input, @"\d+")
      .Cast<Match>()
      .Select(x => Convert.ToInt32(x.Value))
      .ToList();
}

So you could use it like this:

List<int> result = ExtractInts("( 01 - ABCDEFG )");

For some more detailed info on Regular Expressions, see this page (MSDN) or this page (helpful "cheat sheet").

Donut
  • 110,061
  • 20
  • 134
  • 146
1

Check out this blog post: http://weblogs.asp.net/sushilasb/archive/2006/08/03/How-to-extract-numbers-from-string.aspx

A simple program that extracts the number from the String using a regular expression.

class Program
    {
    static void Main(string[] args)
    {
      Console.WriteLine(ExtractNumbers("( 01 - ABCDEFG )"));    // 01
      Console.ReadLine();
    }

    static string ExtractNumbers(string expr)
    {
        return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
    }
}

Hope this helps!

Jompa234
  • 1,228
  • 2
  • 14
  • 24
0
Response.Write(Convert.ToDecimal(string.Join(null, System.Text.RegularExpressions.Regex.Split(TextBox1.Text, "[^\\d .]"))));

This is for both int and decimal numbers.

チーズパン
  • 2,752
  • 8
  • 42
  • 63
0

Try this:

string XYZ = string.Join(null, System.Text.RegularExpressions.Regex.Split(“XYZ  77”, “[^\d]”));
Senjuti Mahapatra
  • 2,570
  • 4
  • 27
  • 38
mangesh
  • 355
  • 4
  • 13
0

You can also using this way to get your appropriate answer..

string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer";
 string[] digits= Regex.Split(sentence, @"\D+");
             foreach (string value in digits)
             {
                 int number;
                 if (int.TryParse(value, out number))
                 {
                     Debug.Log(value);
                 }
             }
LuFFy
  • 8,799
  • 10
  • 41
  • 59