计算字符串中重复的字母

Ole*_*ral 5 javascript regex

我遇到了以下问题:我需要在字符串中找到重复的字符。基本上我想要的是像这样匹配的正则表达式

hello - ["ll"];
here  - ["ee"];
happiness   -  ["pp","ss"];
pupil  -  ["pp"];
Run Code Online (Sandbox Code Playgroud)

我有一个匹配连续重复字符的

  /([a-z])\1+/g
Run Code Online (Sandbox Code Playgroud)

也是将匹配重复字符以及它们之间的所有内容的那个

   /([a-z])(?:.*)\1+/g
Run Code Online (Sandbox Code Playgroud)

但想不出正确的。

daw*_*awg 6

您可以使用

([a-zA-Z]).*(\1)
Run Code Online (Sandbox Code Playgroud)

演示正则表达式


由于您已经澄清您正在寻找一种解决方案来处理字符串中的双字母以外的其他内容,因此您应该使用非正则表达式方法,例如:

使用字符串中的字符数构建关联数组:

var obj={}
var repeats=[];
str='banana'

for(x = 0, length = str.length; x < length; x++) {
    var l = str.charAt(x)
    obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}

console.log(obj)
Run Code Online (Sandbox Code Playgroud)

印刷

{ b: 1, a: 3, n: 2 }
Run Code Online (Sandbox Code Playgroud)

然后构建您的规范数组:

for (var key in obj) {
    if (obj.hasOwnProperty(key) && obj[key]>1) {
        repeats.push(new Array( obj[key]+ 1 ).join( key ));
    }
}
console.log(repeats)
Run Code Online (Sandbox Code Playgroud)

印刷:

[ 'aaa', 'nn' ]
Run Code Online (Sandbox Code Playgroud)