views:

108

answers:

2

Hey everyone,

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

+7  A: 
\((\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
Good solution, I had a longer one, but specifying the `\b` word boundary before the parentheses ensures that we don't have a trailing dash there.
Adam Bellaire
+2  A: 

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
Another possibility, +1. Does not match the "defined groups of characters" requirement, though. However, fixing this would require repeating yourself.
Tomalak