Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Regex to find repeating numbers

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.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)
(d)1+

Explanation:

   # match word boundary
(d) # match digit remember it
1+  # match one or more instances of the previously matched digit
   # 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

(d+)1+

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 :

^(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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...