What am I doing wrong here?
string q = "john s!"; string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty); // clean == "johns". I want "john s";
Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].
Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.
just a FYI
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
would actually be better like
string clean = Regex.Replace(q, @"[^\w\s]", string.Empty);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With