user2530266
user2530266

Reputation: 287

string remove all letters

Why this will print the same result?

string tester = "stUniqueId01";
Debug.WriteLine("ID: " + tester);
var regex = tester.Replace("[^0-9.]", "");
Debug.WriteLine("ID: " + regex);

Output:

ID: stUniqueId01
ID: stUniqueId01

Upvotes: 1

Views: 103

Answers (2)

masual
masual

Reputation: 89

You are using the Replace method from String. It takes strings, not regular expressions. Try:

string tester = "stUniqueId01";
Console.WriteLine("ID: " + tester);
Regex rx = new Regex("[^0-9.]");
var regex = rx.Replace(tester, "");
Console.WriteLine("ID: " + regex);

Result:

ID: stUniqueId01
ID: 01

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

You are calling string.Replace, not Regex.Replace. I think you want:

string tester = "stUniqueId01";
Debug.WriteLine("ID: " + tester);
var regex = new Regex("[^0-9.]");
Debug.WriteLine("ID: " + regex.Replace(tester,""));

or:

string tester = "stUniqueId01";
Debug.WriteLine("ID: " + tester);
var replaced = Regex.Replace(tester,"[^0-9.]","");
Debug.WriteLine("ID: " + replaced);

if you don't intend to reuse the regular expression.

Upvotes: 3

Related Questions