In most regex flavors, you may use simple lookaheads to make sure some text is present or not somewhere to the right of the current locations, and using an alternation operator |
it possible to check for alternatives.
So, we basically have 2 alternatives: there is a &
somewhere in the string after the first 3 alphabets, or not. Thus, we can use
^[A-Za-z]{3}(?:(?=.*&)".*"|(?!.*&).*)$
See the regex demo
Details:
^
- start of string
[A-Za-z]{3}
- 3 alphabets
(?:(?=.*&)".*"|(?!.*&).*)
- Either of the two alternatives:
(?=.*&)".*"
- if there is a &
somewhere in the string ((?=.*&)
) match "
, then any 0+ characters, and then "
|
- or
(?!.*&).*
- if there is no &
((?!.*&)
) in the string, just match any 0+ chars up to the...
$
- end of string.
In PCRE, or .NET, or some other regex flavors, you have access to the conditional construct. Here is a PCRE demo:
^[A-Za-z]{3}(?(?=.*&)".*"|.*)$
^^^^^^^^^^^^^^^^^
The (?(?=.*&)".*"|.*)
means:
(?(?=.*&)
- if there is a &
after any 0+ characters...
".*"
- match "anything here"
-like strings
|
- or, if there is no &
.*
- match any 0+ chars from the current position (i.e. after the first 3 alphabets).