3

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

dlarkin77
  • 867
  • 1
  • 11
  • 27

4 Answers4

5

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

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
3

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)

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
2

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.

Community
  • 1
  • 1
Sandeep Datta
  • 28,607
  • 15
  • 70
  • 90
1

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

Gabber
  • 5,152
  • 6
  • 35
  • 49