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
0
: 294 At:- 7/2/2018 6:39:16 AM
C# extract int from string






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

2
At:- 7/2/2018 5:47:27 PM
Great answer, thanks 0
By : Vinnu - at :- 7/4/2018 3:34:45 PM





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