9

I have a string which contains many characters. I want to remove A-Za-z and white space and be left with the rest. What's the best way to do this?

Here's what I've tried

presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z]", string.Empty);

but I also need to remove white space.

5 Answers 5

10

You can use \s.

For example:

presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z\s]", string.Empty);
3

Without regular expressions:

var chars = str.Where(c => !char.IsLetter(c) && !char.IsWhitespace(c)).ToArray();
var rest = new string(chars);
3

Your regular expression is fine, except for the whitespace. This should work:

string result = Regex.Replace(myString, @"[a-zA-Z\s]+", string.Empty);
1
  • %20 is not the only whitespace in town.
    – mellamokb
    Commented Nov 17, 2012 at 19:20
2

You can use \s to include whitespace.

Regex.Replace(myString, @"[a-z]|[A-Z]|\s", "")

Demo: http://ideone.com/yHG2xw

1

You almost made it. Use this regex expression

[a-zA-Z ]+

It simply includes the whitespace. Adding a + makes it more efficient, as whole series of characters can be replaced at once (internally).

1
  • This doesn't include tabs though.
    – Dan
    Commented Nov 17, 2012 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.