dlarkin77
dlarkin77

Reputation: 879

RegularExpressionValidator - validate that a string does NOT match an expression

I am trying to write a regular expression (for use in an ASP.NET RegularExpressionValidator) so that:

If the string to be validated contains the letter A followed by the letter B, validation should fail.

If the string to be validated contains the letter F followed by any of W, X, Y, Z or any digit, validation should fail.

I've come up with this

(AB)|(F(W|X|Y|Z|[0-9]))

but as far as I can tell, validation will succeed if the input does match that expression.

What do I need to do to make the validation fail if the input does not match that expression?

Thanks very much,

David

Upvotes: 3

Views: 2710

Answers (4)

Gabber
Gabber

Reputation: 5452

You can perform a match against this regex

^(?!^.*?AB)(?!^.*?F[WXYZ\d]).*$

Here a working example. Basically it means "find all the strings except the strings containing AB with an arbitrary number of characters before and after and except those containing an F followed by W,X,Y,Z or a digit". Info at this link provided in Tim Pietzcker's answer

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

This is what negative lookaheads are for

(?!.*AB)(?!.*F[WXYZ\d])

fails on these strings. It doesn't match any text yet (which should be sufficient if all you want to do is check whether there is a match or not), so the match result will always be an empty string

Upvotes: 5

Hans Kesting
Hans Kesting

Reputation: 39265

This would work:

A[^B]|F[^WXYZ0-9]|[^AF].
  • an A followed by anything except a B, or
  • an F followed by anything excepty W,X,Y,Z or digit, or
  • something other that A or F followed by any single character

Note that this would also match "A$" or "@@". If you only want to match "one letter followed by one letter or digit", then use this:

A[AC-Z0-9]|F[A-V]|[B-EG-Z][A-Z0-9]

Regex is better at positive matches.

Note that for the regex validator the entire string must match (if just a substring matches, the validator reports a validation failure)

Upvotes: 3

Sandeep Datta
Sandeep Datta

Reputation: 29335

You can use the logical not operator provided by your programming language to negate the result returned by the match operation there is no need to modify your regex.

Edit: In case the above is not an option please look at these questions 1, 2 and 3.

Upvotes: 2

Related Questions