12

I need to find 1 or more defined groups of characters enclosed in parentheses. If more than one group is present it will be separated with a hyphen.

Example:

(us)
(jp)
(jp-us)
(jp-us-eu)

I've figured out how to find the group if the string only contains one group:

/\(us\)|\(jp\)/

However, I am baffled when it comes to finding more than one, separated by a hypen and in no particular order: (us-jp) OR (jp-us)

Any help is appreciated.

Thanks, Simon

Gumbo
  • 643,351
  • 109
  • 780
  • 844
simonwjackson
  • 1,818
  • 4
  • 25
  • 33
  • Can you clarify what you're looking for? The regex you provide will locate both (us-jp) and (jp-us). – bbg Sep 26 '09 at 18:24

2 Answers2

21
\((\b(?:en|jp|us|eu)-?\b)+\)

Explanation:

\(                     // opening paren
(                      // match group one
  \b                   // word boundary
  (?:en|jp|us|eu)      // your defined strings
  -?                   // a hyphen, optional
  \b                   // another word boundary
)+                     // repeat
\)                     // closing paren

matches:

(us)
(jp) 
(jp-us)
(jp-us-eu)

does not match:

(jp-us-eu-)
(-jp-us-eu)
(-jp-us-eu-)
Tomalak
  • 332,285
  • 67
  • 532
  • 628
3

Try this:

/\([a-z]{2}(?:-[a-z]{2})*\)/

That will match any two letter sequence in parenthesis that my contain more two letter sequences separeted by hypens. So (ab), (ab-cd), (ab-cd-ef), (ab-cd-ef-gh) etc.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Another possibility, +1. Does not match the "defined groups of characters" requirement, though. However, fixing this would require repeating yourself. – Tomalak Sep 26 '09 at 18:29