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";
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";
I suspect ^ doesn't work the way you think it does outside of a character class.
What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.
There appear to be two problems.
I think you want the following regex @"([^a-zA-Z0-9\s])+"
The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.
I got it:
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
Didn't know you could put \s in the brackets