Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for detecting the same character more than five times?

Tags:

regex

php

I'm trying to figure out how to write a regex that can detect if in my string, any character is repeated more than five times consecutively? For example it wouldn't detect "hello", but it would detect "helloooooooooo".

Any ideas?

Edit: Sorry, to clarify, I need it to detect the same character repeated more than five times, not any sequence of five characters. And I also need it to work with any charter, not just "o" like in my example. ".{5,}" is no good because it just detects any sequence of any five characters, not the same character.

like image 204
Jack Sleight Avatar asked Sep 23 '10 14:09

Jack Sleight


People also ask

How do you find multiple occurrences of a string in regex?

Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

How do you repeat a pattern in regex?

A repeat is an expression that is repeated an arbitrary number of times. 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.

Which character stand for one or more occurrences in regex?

A regular expression followed by a plus sign ( + ) matches one or more occurrences of the one-character regular expression. If there is any choice, the first matching string in a line is used.


2 Answers

This should do it

(\w)\1{5,}
  • (\w) match any character and put it in the first group
  • \1{5,} check that the first group match at least 5 times.

Usage :

$input = 'helloooooooooo';
if (preg_match('/(\w)\1{5,}/', $input)) {
 # Successful match
} else {
 # Match attempt failed
}
like image 78
Julien Hoarau Avatar answered Oct 11 '22 23:10

Julien Hoarau


Correction, should be (.)\1{5,}, I believe. My mistake. This gets you:

(.)  #Any character
\1   #The character captured by (.)
{5,} #At least 5 more repetitions (total of at least 6)

You can also restrict it to letters by using (\w)\1{5,} or ([a-zA-Z])\1{5,}

like image 25
eldarerathis Avatar answered Oct 12 '22 01:10

eldarerathis