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
var NumberFromString= string.Join(string.Empty, Regex.Matches(StringWithNumber, @"\d+").OfType<Match>().Select(m => m.Value));
Input: " 121 testing"
Output: "121"
string StringWithNumbers= "121 - Testing";
var data = Regex.Match(StringWithNumbers, @"\d+").Value;
Console.WriteLine(data);
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.
string numbersOnly = new String(phone.Where(Char.IsDigit).ToArray());
Thanks.
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
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly