计算字符串中的重复字母 [英] Count repeated letters in a string
问题描述
我遇到了以下问题:
我需要在字符串中找到重复的字符。
基本上我想要的是正则表达式,它将匹配如此
I'm stuck with the following problem: I need to find repeated characters in a string. Basically what I want is regular expression that will match like that
hello - ["ll"];
here - ["ee"];
happiness - ["pp","ss"];
pupil - ["pp"];
我有一个匹配连续重复字符的那个
I have the one that matches consecutive repeated characters
/([a-z])\1+/g
还会匹配重复的字符和它们之间的所有内容,例如这个
Also the one that will match repeated chars and everything between them like this one
/([a-z])(?:.*)\1+/g
但是找不到正确的。
推荐答案
您可以使用
([a-zA-Z]).*(\1)
既然您已经澄清了您正在寻找一种解决方案,它将处理字符串中除双字母以外的其他内容,您应该使用非正则表达式方法,例如:
Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:
使用字符串中的字符数构建关联数组:
Build an associative array with the count of the characters in the string:
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)
打印
{ b: 1, a: 3, n: 2 }
然后构建一个规范数组:
Then build an array of your specifications:
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]>1) {
repeats.push(new Array( obj[key]+ 1 ).join( key ));
}
}
console.log(repeats)
打印:
[ 'aaa', 'nn' ]
这篇关于计算字符串中的重复字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!