tags:

views:

86

answers:

4

I want to strip away all letters in a string, which are not numeric. Preferably a solution made with Regular Expressions or something. And in C#. How to do that?

+4  A: 

Using Regex:

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

\D is the complement of \d - matches everything that isn't a digit. + will match one or more of them (it usually works a little better than one by one).

Using Linq (on .Net 4.0):

str = String.Concat(str.Where(Char.IsDigit));
Kobi
A: 
string result = System.Text.RegularExpressions.Regex.Replace("text to look for stuff", "pattern", "what to replace it with")
BuildStarted
Umm okay? How is this useful? How does regex work? How do you mysteriously use this 'pattern' thing? And how does this answer the question at all?
Jonas
My assumption was simply that he didn't know how to call a regex replace in c# rather than wanting exact code to do it. After reading the other answers I realized my answer was wanting but thanks for pointing out that I'm wrong.
BuildStarted
A: 
string str = "ab123123abc"
str = Regex.Replace(str, @"[\w]", ""); 

Referenced from http://msdn.microsoft.com/en-us/library/844skk0h.aspx

ZEAXIF
`[\w]` is redundant, you don't need a the character class. `\w` is exactly the same. However, `\w` includes letters and digits (and an underscore), so you end up with special characters and spaces.
Kobi
A: 

i rather like to use the not ^ like ^\d or ^[0-9]

string resultString = null;
try {
    resultString = Regex.Replace(subjectString, @"[^\d]+", "");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Spidfire
Well, that's basically the same, but probably better known. The `try/catch` block isn't needed, the only possible exception is if `subjectString` is `null`, which you better check. You will not get `ArgumentException` for this pattern - it is correct `:)` However, that should be "`[^\d]` or `[^0-9]`"
Kobi