Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find repeating numbers

Tags:

regex

Can anyone help me or direct me to build a regex to validate repeating numbers

eg : 11111111, 2222, 99999999999, etc

It should validate for any length.

like image 483
Charmila Avatar asked Jun 28 '11 14:06

Charmila


People also ask

How do you repeat 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 regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What is Dot Plus in regex?

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.


2 Answers

\b(\d)\1+\b 

Explanation:

\b   # match word boundary (\d) # match digit remember it \1+  # match one or more instances of the previously matched digit \b   # match word boundary 

If 1 should also be a valid match (zero repetitions), use a * instead of the +.

If you also want to allow longer repeats (123123123) use

\b(\d+)\1+\b 

If the regex should be applied to the entire string (as opposed to finding "repeat-numbers in a longer string), use start- and end-of-line anchors instead of \b:

^(\d)\1+$ 

Edit: How to match the exact opposite, i. e. a number where not all digits are the same (except if the entire number is simply a digit):

^(\d)(?!\1+$)\d*$  ^     # Start of string (\d)  # Match a digit (?!   # Assert that the following doesn't match:  \1+  # one or more repetitions of the previously matched digit  $    # until the end of the string )     # End of lookahead assertion \d*   # Match zero or more digits $     # until the end of the string 
like image 155
Tim Pietzcker Avatar answered Sep 24 '22 21:09

Tim Pietzcker


To match a number of repetitions of a single digit, you can write ([0-9])\1*.

This matches [0-9] into a group, then matches 0 or more repetions (\1) of that group.

You can write \1+ to match one or more repetitions.

like image 30
SLaks Avatar answered Sep 22 '22 21:09

SLaks