Regex to match alphanumeric and spaces
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";
Solution 1:
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);
Solution 2:
This:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20 is ascii hex for 'space' character
you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.