Looking for a regular expression in PHP
or javaScript
that return true if 3 or more of the same characters (regardless of its 'position') are found:
"q6dqaqb" -> return true
"qyakc6m" -> return false
"jjfffua" -> return true
"--rr4-c" -> return true
"-qsev-m" -> return false
I have tried to the best of my ability to search for a solution like this
( Regular expression: same character 3 times )
but this does not fit the requirement.
Edit:Thank you all for the swift reply. The PHP solution is awesome too.
Based on the answers, What is the difference between these regex:
(.)(?=.*\1.*\1)
.*(.).*\1.*\1.*
(?=.*(.).*\1.*\1)
Sorry, I can't live with myself until I understand what it means.
使用先行查找三个中的第一个:
/(.)(?=.*\1.*\1)/
This expression
(?=.*(.).*\1.*\1)
might likely ensure that and to get the entire string, we can expand it to:
^(?=.*(.).*\1.*\1).*$
$re = '/^(?=.*(.).*\1.*\1).*$/m';
$str = 'q6dqaqb
qyakc6m
jjfffua
--rr4-c
-qsev-m
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
array(3) {
[0]=>
array(2) {
[0]=>
string(7) "q6dqaqb"
[1]=>
string(1) "q"
}
[1]=>
array(2) {
[0]=>
string(7) "jjfffua"
[1]=>
string(1) "f"
}
[2]=>
array(2) {
[0]=>
string(7) "--rr4-c"
[1]=>
string(1) "-"
}
}
const regex = /^(?=.*(.).*\\1.*\\1).*$/gm; const str = `q6dqaqb qyakc6m jjfffua --rr4-c -qsev-m `; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
You can try this /(.).*\\1.*\\1/
.
Demo:
var regex = /(.).*\\1.*\\1/; console.log(regex.test("q6dqaqb")) console.log(regex.test("qyakc6m")) console.log(regex.test("jjfffua")) console.log(regex.test("--rr4-c")) console.log(regex.test("-qsev-m"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.