elizac
elizac

Reputation: 11

C# Regex to disallow whitespaces

I'm trying to write a validation with Regex, and I had a no whitespaces variable, but it's throwing an error (despite getting the regex from another similar code example).

var noSpaces = new Regex(@"?!.* ");
var hasNum = new Regex(@"[0-9]+");
var isValid = noSpaces.IsMatch(input) && hasNum.IsMatch(input);

The code is within a method that verifies password specifications, and this one pulls the error system.text.regularexpressions.regexparseexception invalid pattern. So, there has to be something wrong with the no whitespace regex input. The isValid bool is then used in an if statement, to either make the user re-input the password or move to the next method.

(I'm relatively new to C# and regex, so it could just be a simple typo, but I'm not sure what it is. Thanks!)

Upvotes: 0

Views: 406

Answers (1)

gunr2171
gunr2171

Reputation: 17579

If all you're doing is simply testing if a string has any whitespace characters or not, the only pattern you need is \s. One or more match will indicate that there are whitespaces in the input.

Regex whitespacePattern = new Regex(@"\s");
bool inputHasWhitespace = whitespacePattern.IsMatch(input);

To explain why ?!.* is an invalid pattern:

The ? symbol is a quantifier for the previous symbol meaning "zero or one". For example a\d? would match on an "a" followed by zero or one digits.

But, there isn't a symbol proceeding ?, thus it's invalid.

Now, you could have been trying to do a negative lookahead. That would be (?!.*), with the parentheses. If you're incorporating multiple password validation rules into one regex pattern, you may need to resort to that. But for making a single regex pattern to check if there are any whitespace characters, it's not necessary.

Upvotes: 2

Related Questions