Reputation: 1378
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
Reputation: 785146
Use a lookahead based regex like this:
(?=.*?(?:electric|acoustic|guitar|drums))^(?:electric|acoustic|) ?(?:guitar|drums|)$
Upvotes: 2
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