0

I have a string which can contain values both in Character and Numeral format along with some special characters like <>.So as per my requirement i have to remove these special characters and Character from the string.

Here is the string example..

string s = "O9668253";
string s2 = "<O>9668253";

And i need output like..

string s = "9668253";
string s2 = "9668253";

So how can i get this here .Please help me..

Stígandr
  • 2,874
  • 21
  • 36
shubham Hegdey
  • 507
  • 5
  • 8
  • 15

2 Answers2

3

You can just use LINQ. If I understand correctly you just want numbers:

string s = "<O>9668253";
string nums = new string(s.Where(char.IsDigit).ToArray());

or if you want letters also:

string s = "<O>9668253";
string lettersAndNums = new string(s.Where(char.IsLetterOrDigit).ToArray());

if you want the non-digits, just negate it. You'll have to write out the lambda expression:

string s = "<O>9668253";
var nums = new string(s.Where(c => !char.IsDigit(c)).ToArray());
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
1

similar question: How do I remove all non alphanumeric characters from a string except dash?

Assuming you want to remove all non-numeric characters:

Replace [^0-9] with an empty string.

Regex rgx = new Regex("[^0-9]");
str = rgx.Replace(str, "");

@Steve - thanks for pointing out the error

Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27
  • 1
    Did you read the question correctly? It seems to me that he wants to keep the numbers and discard the non-numbers. – Steve Sep 24 '14 at 12:24
  • ah right, i thought he just wanted to remove non-alphanumeric, will modify the answer. – user1666620 Sep 24 '14 at 12:25