开发者

Check if a String only contains digits and the digits are not the same using REGEX?

开发者 https://www.devze.com 2022-12-10 05:25 出处:网络
111111111 - Invalid A121278237 - Invalid 7777777777 - In开发者_开发知识库valid 121263263 - Valid
111111111 - Invalid
A121278237 - Invalid
7777777777 - In开发者_开发知识库valid

121263263 - Valid
111111112 - Valid


^([0-9])(?!\1+$)[0-9]+$

should work. It needs a string of at least two digits to match successfully.

Explanation:

  1. Match a digit and capture it into backreference #1: ([0-9])

  2. Assert that it's impossible to match a string of any length (>1) of the same digit that was just matched, followed by the end of the string: (?!\1+$)

  3. Then match any string of digits until the end of the string: [0-9]+$

EDIT: Of course, in Java you need to escape the backslash inside a string ("\\").


  1. take a [0-9] regex and throw away strings that not only contain digits.
  2. take the first character, and use it as a regex [C]+ to see if the string contains any other digits.


Building on Tim's answer, you eliminate the requirement of "at least two digits" by adding an or clause.

^([0-9])(?!\1+$)[0-9]+$|^[0-9]$

For example:

String regex = "^([0-9])(?!\\1+$)[0-9]+$|^[0-9]$";
boolean a = "12".matches(regex);
System.out.println("a: " + a);
boolean b = "11".matches(regex);
System.out.println("b: " + b);
boolean c = "1".matches(regex);
System.out.println("c: " + c);

returns

a: true
b: false
c: true
0

精彩评论

暂无评论...
验证码 换一张
取 消