Regex to match alphanumeric and spaces

Viewed 156852

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";
10 Answers

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

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.

  1. You're using the ^ outside a [] which matches the start of the line
  2. You're not using a * or + which means you will only match a single character.

I think you want the following regex @"([^a-zA-Z0-9\s])+"

bottom regex with space, supports all keyboard letters from different culture

 string input = "78-selim güzel667.,?";
 Regex regex = new Regex(@"[^\w\x20]|[\d]");
 var result= regex.Replace(input,"");
 //selim güzel

The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.

This regex will help you to filter if there is at least one alphanumeric character and zero or more special characters i.e. _ (underscore), \s whitespace, -(hyphen)

string comparer = "string you want to compare";
Regex r = new Regex(@"^([a-zA-Z0-9]+[_\s-]*)+$");

if (!r.IsMatch(comparer))
{
   return false;
}    
return true;

Create a set using [a-zA-Z0-9]+ for alphanumeric characters, "+" sign (a quantifier) at the end of the set will make sure that there will be at least one alphanumeric character within the comparer.

Create another set [_\s-]* for special characters, "*" quantifier is to validate that there can be special characters within comparer string.

Pack these sets into a capture group ([a-zA-Z0-9]+[_\s-]*)+ to say that the comparer string should occupy these features.

[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]

Above syntax also accepts space

Related