3

I want to reject strings that start with BT(uppercase and lowercase included)

Original regex:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z] [A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})$

negative lookbehind regex:

(?<!([bB][tT]))(^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z] [A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})$)

but this regex is still accepting BT444CC The second group is capturing t how can i prevent this?

wolf
  • 146
  • 2
  • 15
Codemaster
  • 145
  • 2
  • 13

1 Answers1

2

You do not need a lookbehind, you need a lookahead at the start of the string, (?![Bb][Tt]).

Also, you need to enclose the whole pattern with a non-capturing group, else, the lookahead will only restrict the part before the first |.

You can use

^(?![Bb][Tt])(?:[Gg][Ii][Rr] 0[Aa]{2}|([A-Za-z][0-9]{1,2}|([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2}|([A-Za-z][0-9][A-Za-z]|[A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))\s?[0-9][A-Za-z]{2})$

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    @Codemaster That is not the issue with the current question, it works as per the original post requirements. If you need to allow any amount of whitespace at any location you need, just add `\s*` at those locations. You suggested `(\s)*?`, but the parentheses and `?` are redundant. – Wiktor Stribiżew Dec 13 '20 at 18:51