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#?
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly