最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Match first group, second group or both in regex - Stack Overflow

programmeradmin1浏览0评论

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> 

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> 
Share Improve this question edited Dec 6, 2012 at 11:19 Kristian asked Dec 6, 2012 at 11:01 KristianKristian 1,3884 gold badges17 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

Use a lookahead based regex like this:

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

Live Demo

发布评论

评论列表(0)

  1. 暂无评论