0

I've tried new Regex("a-zA-Z0-9").Replace(myString, string.Empty) but apparently that is not correct.

2 Answers 2

5

The correct regex would be [a-zA-Z0-9].

The regular expression a-zA-Z0-9 matches the literal string a-zA-Z0-9 whereas the character class [a-zA-Z0-9] matches any of the characters in the ranges a-z, A-Z or 0-9.

In addition, these classes have shorthands (sort of).

  • \d represents the class of digits, that is [0-9].
  • \w represents the class of alphanumerical characters, as well as underscore, that is [0-9A-Za-z_].

Useful links:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I knew I was missing something simple. ;) +1
1

Just for laughs you could also do it like this....

string newString = new string(s.Where(c => !char.IsLetterOrDigit(c)).ToArray());

(much, much slower the first time through...then subsequent runs, faster)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.