Match the first group, the second group, or both in a regular expression

I have the following regex:

(electric|acoustic) (guitar|drums) 

I need to combine:

  electric guitar electric drums acoustic guitar acoustic drums electric acoustic guitar drums 

I tried to use? after both groups, but then it corresponded to everything. Thanks!

Edit:

 <script type="text/javascript"> var s = "electric drums"; if(s.match('^(?:electric()|acoustic())? ?(?:guitar()|drums())?(?:\1|\2|\3|\4)$')){ document.write("match"); } else { document.write("no match"); // returns this } </script> 
+4
source share
2 answers

Use a lookahead based regex like this:

 (?=.*?(?:electric|acoustic|guitar|drums))^(?:electric|acoustic|) ?(?:guitar|drums|)$ 

Live demo

+2
source

One way would be to write:

 ^((electric|acoustic) (guitar|drums)|(electric|acoustic|guitar|drums))$ 

or (because you don't need parentheses to write)

 ^(?:(?:electric|acoustic) (?:guitar|drums)|(?:electric|acoustic|guitar|drums))$ 

You can also use the trick if you don't like repeating:

 ^(?:electric()|acoustic())? ?(?:guitar()|drums())?(?:\1|\2|\3|\4)$ 

(?:\1|\2|\3|\4) ensures that at least one of the previous empty capture groups ( () ) participated in the match.

+3
source

All Articles