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.
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.
+: 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.
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.
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.
\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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With