Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if any one character is repeated at least a specified number of times in a row

Tags:

regex

php

I know this could probably be done without regular expressions, but I'd rather make the solution short and elegant than a block of hackjob code.

What I'm looking to accomplish is to determine if any character is repeated at least X times in a row in a string of non-predefined length. The threshold for repetition, X, can be hard coded because the code it will be used in won't be changing much. The repeated character itself is unimportant, I only care to know if such repetition exists.

For example, if the threshold is set to 4:

aaaabcd   = Match
aaabbcd   = No Match
abbbbcd   = Match
aabaaad   = No Match
aAaAbcd   = No Match

If the repetition threshold is set to 1, any input non-empty input string should match and if the repetition threshold is set to longer than the input string, it should fail to match.

I have a feeling the solution is going to involve back references, but I'm not familiar enough with them myself to work out a solution.

If anybody is curious, the language I'll be implementing this in will be PHP, so code snippets are welcome!

like image 488
Mr. Llama Avatar asked Nov 29 '25 15:11

Mr. Llama


1 Answers

You can use the regex:

(.)\1{3}

which can be used in PHP as:

if(preg_match('/(.)\1{3}/',$input)) {
  echo "$input matches\n";
}

Ideone Link

like image 115
codaddict Avatar answered Dec 01 '25 05:12

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!