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
2010-06-17 14:50:21
A:
string result = System.Text.RegularExpressions.Regex.Replace("text to look for stuff", "pattern", "what to replace it with")
BuildStarted
2010-06-17 14:50:50
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
2010-06-17 16:37:14
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
2010-06-17 17:27:52
A:
string str = "ab123123abc"
str = Regex.Replace(str, @"[\w]", "");
Referenced from http://msdn.microsoft.com/en-us/library/844skk0h.aspx
ZEAXIF
2010-06-17 14:51:42
`[\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
2010-06-17 14:58:09
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
2010-06-17 15:04:20
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
2010-06-17 15:08:42