0

I'm looking for a single line regular expression which matches a pattern with optional parentheses. When the parentheses are present they should not be included in the matched pattern.

The following bold text demonstrates what should / shouldn't match:

Should Match:

"Title Description (AAA123)"

"(ABC000) Title Description"

"Title Description DEF999"

"Title - RST321 - Description"

Shouldn't Match:

"Title Description AB123"

"Title Description CCC456a"

"Title Description (ABE999c)"

nhahtdh
  • 52,949
  • 15
  • 113
  • 149
Brian Scott
  • 8,837
  • 6
  • 40
  • 67

1 Answers1

3

Try this regex:

\b[a-zA-Z]{3}\d{3}\b

This matches:

# \b          - A word boundary,
# [a-zA-Z]{3} - followed by 3 letters,
# \d{3}       - followed by 3 digits,
# \b          - followed by a word boundary.

The regex doesn't care about parentheses, like requested, but doesn't match strings that are too long.

Cerbrus
  • 60,471
  • 15
  • 115
  • 132
  • 1
    You will also match `___345` and `234456` – nhahtdh Feb 12 '13 at 14:11
  • @nhahtdh: Whoops, I didn't think of `\w` also matching those. Edited, thanks! – Cerbrus Feb 12 '13 at 14:12
  • @Cerbrus: Excellent, the \b was the missing key for me. I didn't know how to match either empty space or a parenthesis at the same time. Thanks. – Brian Scott Feb 12 '13 at 14:16
  • No problem, @Brian! I'd suggest having a look at [this site](http://www.regular-expressions.info), it has a lot of useful info on regexes. Thanks for accepting my answer ^_^ – Cerbrus Feb 12 '13 at 14:26