How to find and extract only number from string in C#?


I have a string with numbers in it, for example here is the string "121 testing your City", now, I would like to extract only "121" from the string, how can I do that using C#?


Asked by:- Vinnu
1
: 12231 At:- 7/2/2018 6:39:16 AM
C# extract int from string







2 Answers
profileImage Answered by:- neena

You can extract the number from a string using Regex, here is the regex that should work

Method first:

var NumberFromString= string.Join(string.Empty, Regex.Matches(StringWithNumber, @"\d+").OfType<Match>().Select(m => m.Value));

Input: " 121 testing"

Output: "121"

Second Method:

string StringWithNumbers= "121 - Testing";

var data = Regex.Match(StringWithNumbers, @"\d+").Value;

Console.WriteLine(data);

Third method:

Now it may be possible that your string may have a number like this "121/1 Testing answer", which may contain special characters also, so in that case, you would need a regex like below to remove special characters (-,/)

   Regex rgx = new Regex("[^0-9-/]");
  
   var Number = rgx.Replace("121/1 Testing String", "");  //121/1
   var remainingString = Model.Street.Replace(Number, "");   

In this way, you can do this using Regex and change it according to your need.

Fourth way using char.IsDigit

string numbersOnly = new String(phone.Where(Char.IsDigit).ToArray());

Thanks.

2
At:- 7/2/2018 5:47:27 PM Updated at:- 9/27/2022 7:39:08 AM
Great answer, thanks 0
By : Vinnu - at :- 7/4/2018 3:34:45 PM


profileImage Answered by:- vikas_jk

You can also get only numbers using char.IsDigit without regex.

string a = "hello1234World";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);

Console.WriteLine(val);

Thanks

0
At:- 9/27/2022 11:00:21 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use