I want to match strings in the format of A0123456, E0123456, or IN:A0123456Q, etc. I originally made this regex
^(IN:)?[AE][0-9]{7}Q?$
but it was matching IN:E012346 without the Q at the end. So I created this regex
(^IN:[AE][0-9]{7}Q$)|(^[AE][0-9]{7}$)
Is there any way to shorten this regex so that it requires both IN: and Q if they are present, but not if neither are present?
Edit: The regex will be used in Ruby.
Edit 2: I changed the regex to reflect that I was matching the wrong strings, as it would still match IN:A0123456.
Edit 3: Both answers below are valid, but since I am using Ruby 2.0 and prefer a regex expression I can use in case I change my application and don't want to use the Ruby flavor of subexpression calls, I chose to accept matt's answer.