Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove alphabets from a string

Tags:

c#

I want to remove alphabets from a string. What is the best way to do it. To be more precise, i have MAC address of a system, and I want to extract only the numbers from it. I have found this article or stackoverflow. link text

I want to know, if using the regex is the best way or there are other ways to do it (maybe using LINQ).

like image 390
Sandy Avatar asked Mar 01 '26 03:03

Sandy


2 Answers

To get the digits, you can use this regex:

var digits = Regex.Replace(text, @"\D", "");

\D matches anything that is not a digit, so removing those will give you the remaining digits.

like image 110
Brian Rasmussen Avatar answered Mar 02 '26 16:03

Brian Rasmussen


The LINQ approach would be as follows:

string input = "12-34-56-78-9A-BC";
string result = new String(input.Where(Char.IsDigit).ToArray());

Non-LINQ / 2.0 approach:

string result = new String(Array.FindAll(input.ToCharArray(),
                    delegate(char c) { return Char.IsDigit(c); }));
like image 44
Ahmad Mageed Avatar answered Mar 02 '26 17:03

Ahmad Mageed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!