重复字符的正则表达式是什么?

重复字符的正则表达式是什么?

问题描述:

I'm writing a password strength checker in PHP, and I'm using Regular Expressions to calculate various parameters for the strength calculation. I need to be able to check the number of repeating consecutive characters in a string. For example:

baaabaaablacksheep would return 5

sillystring would return 1

and so on...

我正在用PHP编写密码强度检查器,我正在使用正则表达式计算各种参数 强度计算。 我需要能够检查字符串中重复连续字符的数量。 例如: p>

baaabaaablacksheep code>将返回 5 code> p>

sillystring code >将返回 1 code> p>

 等等...... 
  code>  pre> 
  div>

You can use regex with \1+ to find the repeating characters, and then use strlen() to count them. Try something like:

$str = 'baaabaaablacksheep';    
$repeating = array();
preg_match_all('/(\w)(\1+)/', $str, $repeating);

if (count($repeating[0]) > 0) {
    // there are repeating characters
    foreach ($repeating[0] as $repeat) {
        echo $repeat . ' = ' . strlen($repeat) . "
";
    }
}

Output:

aaa = 3
aaa = 3
ee = 2

Another variant of the solution posted by newfurniturey:

$passarr = Array('baaabaaablacksheep', 'okstring', 'sillystring');

foreach($passarr as $p) {
   $repeats = 0;
   preg_match_all('/(.)(\1+)/', $p, $matches, PREG_SET_ORDER);
   foreach($matches as $m) $repeats += strlen($m[2]);
   printf("%s => %d repeats
", $p, $repeats);
}

prints:

baaabaaablacksheep => 5 repeats
okstring => 0 repeats
sillystring => 1 repeats