Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find groups of letters with regex

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

like image 546
simonwjackson Avatar asked Sep 26 '09 18:09

simonwjackson


2 Answers

\((\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-)
like image 97
Tomalak Avatar answered Oct 05 '22 07:10

Tomalak


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.

like image 37
Gumbo Avatar answered Oct 05 '22 07:10

Gumbo