javascript 如何找到3个或更多连续字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15688193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find 3 or more consecutive characters?
提问by catherine
I'm making a password checking. One of those functions is to find if the inputted password is consecutively repeated. I do not have codes yet because I don't know how to do it.
我正在检查密码。这些功能之一是查找输入的密码是否连续重复。我还没有代码,因为我不知道该怎么做。
I found this one RegEx match two or more same character non-consecutivebut it only match repeated commas.
我发现这个RegEx 匹配两个或多个非连续的相同字符,但它只匹配重复的逗号。
Here's are the scenarios:
以下是场景:
5236aaa121 - Repeated pattern because a
is consecutively repeated 3 times
5236aaa121 - 重复模式因为a
连续重复 3 次
2312aa32aa - No repeated character
2312aa32aa - 无重复字符
111111asd - Repeated pattern because 1
is consecutively repeated many times
111111asd - 重复模式因为1
连续重复多次
回答by jmar777
Use a back reference: /(.)\1\1/
使用反向引用: /(.)\1\1/
Example:
例子:
var hasTripple = /(.)/.test('xyzzzy');
回答by Steve Seo
How about the following one?
下一个怎么样?
(.)\1{2,}
(.)\1{2,}
回答by user1717674
Try this regex: (.)\1\1+
试试这个正则表达式: (.)\1\1+
/(.)+/g
The dot matches any character, then we are looking for more than one in a row. i tested it on http://regexpal.com/and i believe it does what you want
点匹配任何字符,然后我们要连续查找多个字符。我在http://regexpal.com/上对其进行了测试,我相信它可以满足您的需求
you can use this like this:
你可以这样使用它:
str.match(/(.)+/g).length
just check that it is 0
只需检查它是否为 0
to see this in action.... http://jsfiddle.net/yentc/2/
看到这个在行动.... http://jsfiddle.net/yentc/2/
回答by Kanagaraj M
You just iterate the string by for loop and compare one to next if both are same then increase by one(declare one variable for count).. At last check count value if it is greater then 0 then the string is repeated pattern...
您只需通过 for 循环迭代字符串并比较一个和下一个,如果两者相同,则增加一(声明一个变量用于计数)。最后检查计数值,如果它大于 0,则该字符串是重复的模式...
回答by jugg1es
You could do something like this:
你可以这样做:
var password = '5236aaa121';
for(var i = 0; i< password.length; i++) {
var numberOfRepeats = CheckForRepeat(i, password, password.charAt(i));
//do something
}
function CheckForRepeat(startIndex, originalString, charToCheck) {
var repeatCount = 1;
for(var i = startIndex+1; i< password.length; i++) {
if(originalString.charAt(i) == charToCheck) {
repeatCount++;
} else {
return repeatCount;
}
}
return repeatCount;
}