Regex – Regular expressions to match flight number

regex

Basically, I want to write a regex to match flight number with format AA123 or AA1234.

\b[A-Z]{2}\d{3,4}\b

That is two letters plus 3 or 4 digits. My solution and results are shown in the picture. I cannot understand why it fails when omitting spaces between words.

Best Answer

In fact, Airline codes may contain numbers. Ex: S7

Therefore the better regexp would be

\b([A-Z]{2}|[A-Z]\d|\d[A-Z])\s?\d{3,4}\b

if you really need finding flight numbers in strings without spaces. (Case sensitive) First negative lookbehind and the last non-digits group serve as boundaries.

(?<!([A-Z0-9]))(([A-Z]{2}|[A-Z]\d|\d[A-Z])\s?\d{3,4})(?:\D)