Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove characters from a string using LINQ

I'm having a String like

XQ74MNT8244A

i nee to remove all the char from the string.

so the output will be like

748244

How to do this? Please help me to do this

like image 845
Thomas Anderson Avatar asked Dec 06 '10 12:12

Thomas Anderson


3 Answers

Two options. Using Linq on .Net 4 (on 3.5 it is similar - it doesn't have that many overloads of all methods):

string s1 = String.Concat(str.Where(Char.IsDigit));

Or, using a regular expression:

string s2 = Regex.Replace(str, @"\D+", "");

I should add that IsDigit and \D are Unicode-aware, so it accepts quite a few digits besides 0-9, for example "542abc٣٤".
You can easily adapt them to a check between 0 and 9, or to [^0-9]+.

like image 189
Kobi Avatar answered Nov 14 '22 12:11

Kobi


new string("XQ74MNT8244A".Where(char.IsDigit).ToArray()) == "748244"
like image 41
Tim Robinson Avatar answered Nov 14 '22 11:11

Tim Robinson


string value = "HTQ7899HBVxzzxx";
Console.WriteLine(new string(
     value.Where(x => (x >= '0' && x <= '9'))
     .ToArray()));
like image 6
Aliostad Avatar answered Nov 14 '22 11:11

Aliostad