Kristian
Kristian

Reputation: 1378

Match first group, second group or both in regex

I have the following regex:

   (electric|acoustic) (guitar|drums)

What I need is to match:

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

I tried using the ? after both groups, but then it matched 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> 

Upvotes: 5

Views: 3904

Answers (2)

anubhava
anubhava

Reputation: 785146

Use a lookahead based regex like this:

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

Live Demo

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

One way would be to spell it out:

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

or (because you don't need the capturing parentheses)

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

You can also use a trick if you don't like to repeat yourself:

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

The (?:\1|\2|\3|\4) makes sure that at least one of the previous empty capturing groups (()) participated in the match.

Upvotes: 4

Related Questions