-1

This is what i have already.

^[abceghj-prstw-z][a-np-z]$

I am trying to form regex pattern with these requirements: First position can be any letter but d,f,i,q,u,v. Second position can be any letter but o. The first and second position can't be BG, GB, NK, KN, TN, NT, ZZ.

So for example string "ap" = true.

ao = false (because second position is o).

gb = false (because it cant be gb)

I am pretty new with regular expressions so any help would be great. Thanks.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
eMKa
  • 3
  • 5

3 Answers3

1

You need to make use of negative lookahead to make the regex fail if those specific patterns exist:

^(?i)(?!(bg)|(gb)|(nk)|(kn)|(tn)|(nt)|(zz))[abceghj-prstw-z][a-np-z]$

(?i) makes it case-insensitive.

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

As answered here you may add negative lookahead to exclude forbidden symbols from the beginnig of your regex:

^(?!bg|gb|nk|kn|tn|nt|zz)[abceghj-prstw-z][a-np-z]$
Jakub Ch.
  • 3,577
  • 3
  • 24
  • 43
0

You can use negative lookaheads or negative lookbehinds if you don't want to check the exceptions (gb, ...) manually. Here's an example with a negative lookbehind:

Pattern p = Pattern.compile("[abceghj-prstw-z][a-np-z](?<!gb|bg|nk|kn|tn|nt|zz)", Pattern.CASE_INSENSITIVE);
List<String> inputs = Arrays.asList("ap", "apo", "AP", "GB", "gb", "gg");
for (String input : inputs) {
    System.out.println(input + " " + p.matcher(input).matches());
}

Prints:

ap true
apo false
AP true
GB false
gb false
gg true
steffen
  • 16,138
  • 4
  • 42
  • 81