假设我们有一个像“catdogbirdbirdcat”这样的字符串。比如说“猫”是否恰好出现两次而“狗”恰好出现一次的最佳方法是什么?
(cat|dog)
我们可以将我们的字符串与此正则表达式匹配并获取一个数组并计算匹配元素。或者我们可以做两个单独的正则表达式,一个用于猫,一个用于鸟类,然后从那里开始。
有没有办法在一次传递中使用一个正则表达式?
答案 0 :(得分:3)
嗯,我不知道这是不是最好的方式,而且非常难看。但是,这是一种方法:
/
^ #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).)*$)/
答案 1 :(得分:1)
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++;
}