Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

regex - Regular Expression to check for repeating characters

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...