Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to check for repeating characters

Tags:

regex

I had to create a regular expression that allows in either the text "*ALL" (case independent) OR characters in the ranges a-z, A-Z and 0-9 which must be 17 characters long. This I have done without any problems:

^([\*][Aa][Ll][Ll]|[a-zA-Z0-9]{17})$

The problem I am having is how to alter it so that it picks up if just the same character is entered a number of times (e.g. 17 x's).

like image 957
user1645365 Avatar asked Sep 04 '12 07:09

user1645365


2 Answers

In order to do that you'd need to use the catching parentheses. It's a concept in which whatever you surround with parentheses will be captured into the memory of the regular expression parser.

So if you have the following expression:

(\w)\1+

it will match a single word character: [a-zA-Z0-9_] and the same character(s) after it. Because the parentheses caught and memorised what was stored inside them.

So in your case:

^((?:\*[aA][lL]{2})|([a-zA-Z0-9])\1{17})$

where the (?:) is a non capturing parentheses.

You can also use the \1{1,17} construct which means the character should be repeated from 1 to 17 times.

On another note I think that using a regular expression here is a bit overkill. You should probably save the string, lowercase it then compare it to '*all'. If it's not equal then you can use the regular expression ^([a-zA-Z0-9])\1{17}$ for A LOT more readability.

like image 79
norbitheeviljester Avatar answered Oct 31 '22 17:10

norbitheeviljester


you can use a backreference, if your implementation language supports it

try ([a-zA-Z0-9])\1{16}

the \1 refers to the previously matched group ()

like image 41
Hachi Avatar answered Oct 31 '22 18:10

Hachi