【问题标题】:Counting the number of times two different words appear in a string - possible with just one regular expression?计算两个不同单词出现在字符串中的次数——可能只用一个正则表达式?
【发布时间】:2011-09-13 06:36:13
【问题描述】:

假设我们有一个像“catdogbirdbirdcat”这样的字符串。确定“猫”是否恰好出现两次和“狗”是否恰好出现一次的最佳方法是什么?

 (cat|dog)

我们可以将我们的字符串与这个正则表达式进行匹配,并获取一个数组并计算匹配的元素。或者我们可以做两个单独的正则表达式,一个用于猫,一个用于鸟类,然后从那里开始。

有没有办法一次性使用一个正则表达式?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    好吧,我不知道这是否是最好的方法,而且它很丑陋。但是,这是一种方法:

    /
      ^                  #The start of the string.
    (?=                  #A non-capturing lookaround.
                         #so that you can check both conditions.
        (?:              #A non-capturing group.
          (?:(?!cat).)*  #Capture text, that doesn't have cat included.
          cat            #Check for the text cat
          (?:(?!cat).)*  #See above.
        ){2}             #Two of these
        $                #The end of the string.
      )
      (?=                #Then do the same for dog
        (?:(?!dog).)*
        dog
        (?:(?!dog).)*
        $
      )                  #Only one dog though.
    /x                   #The x flag just means ignore whitespace for readability.
                         #You can also do this though:
    
    /^(?=(?:(?:(?!cat).)*cat(?:(?!cat).)*){2}$)(?=(?:(?!dog).)*dog(?:(?!dog).)*$)/
    

    【讨论】:

    • 哇!当你这样说时,似乎只计算来自 (cat|dog) 的匹配项要简单得多。谢谢。只是想确保我没有遗漏一些明显的东西。
    【解决方案2】:

    嗯……其他人可以接手……我得回家了。但无论如何,这就是我的做法。

    var ar = "catdogbirdbirdcat".match(/(cat|dog|bird)/g).sort()
    var i = 0;
    while(ar[ar.lastIndexOf(ar[i])] != undefined) {
      i = ar.lastIndexOf(ar[i]);
      //somehow get it in an object
      console.log(ar[i] + " " + (i - ar.indexOf(ar[i]) + 1));
      i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2014-04-29
      • 2013-07-26
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      相关资源
      最近更新 更多