user1 user1 -4 years ago 73
C# Question

Regex to exclude non-word Characters but leave spaces

I am trying to write a

Regex
to stop a use entering invalid characters into a postcode field.

from this link I manged to exclude all "Non-word" characters like so.

Regex regex = new Regex(@"[\W_]+");
string cleanText = regex.Replace(messyText, "").ToUpper();


But this also excludes the "Space" characters.

I am sure this is possible but I find regex very confusing!

Can someone help out with an explanation of the regex pattern used?

Answer Source

You may use character class subtraction:

[\W_-[\s]]+

It matches one or more non-word and underscore symbols with the exception of whitespace characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download