I have a string in php like this.
$str = "ABCCCDE" //Contains repeated character CCC more than 2 times
I want to know if there is any repeated characters more than 2 times using regular expression.
Thanks in advance
An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once. An expression followed by '? ' may be repeated zero or one times only.
The next token is the dot, which matches any character except newlines. The dot is repeated by the plus. The plus is greedy. Therefore, the engine will repeat the dot as many times as it can. The dot matches E, so the regex continues to try to match the dot with the next character.
The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.
Perl has long been considered the benchmark for powerful regular expressions. PHP uses a C library called pcre to provide almost complete support for Perl's arsenal of regular expression features.
if (preg_match('/(.)\\1{2}/', $str))
echo "Has 3 same characters consecutively!";
The (.)
will match any character (except new lines), and the \1
will match a pattern same as the first matched group — in this case, the character we've just matched. So this RegEx will match 3 same consecutive characters.
You can use:
'/(.)\1\1/'
E.g.:
preg_match('/(.)\1\1/', $str, $matches);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With