开发者

Counting the number of times two different words appear in a string - possible with just one regular expression?

开发者 https://www.devze.com 2023-04-04 04:32 出处:网络
Say we have a string like \"catdogbirdbirdcat\". What\'s the best way to determine, say, whether \"cat\" occurs exactly twice and \"dog\" occurs exactly once?

Say we have a string like "catdogbirdbirdcat". What's the best way to determine, say, whether "cat" occurs exactly twice and "dog" occurs exactly once?

 (cat|dog)

We can match our string against this regex and get an array back and count up matching elements. Or w开发者_StackOverflowe could do two separate regexes, one for cats and one for birds, and go from there.

Is there a way to do this with one regular expression all in one pass?


Well, I don't know if it's the best way, and it's pretty ugly. However, here is one method:

/
  ^                  #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).)*$)/


Well... someone else can take this up... I've got to get home. But in any case, this is how I'd do it.

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++;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号