111111111 - Invalid
A121278237 - Invalid
7777777777 - Invalid
121263263 - Valid
111111112 - Valid
views:
362answers:
3
+2
A:
- take a [0-9] regex and throw away strings that not only contain digits.
- take the first character, and use it as a regex [C]+ to see if the string contains any other digits.
Zed
2009-11-06 11:44:50
For production code I might well prefer this approach: do the check in separate steps using very simple regular expressions. This way the code would be more readily understood by other people on the team. So +1 for this too.
Jonik
2009-11-06 13:14:09
+11
A:
^([0-9])(?!\1+$)[0-9]+$
should work. It needs a string of at least two digits to match successfully.
Explanation:
Match a digit and capture it into backreference #1:
([0-9])
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+$)
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 ("\\"
).
Tim Pietzcker
2009-11-06 11:47:42
"assumes a string of at least two digits" -> "assumes a string with length of 2 or more"? I mean the regex seems to work correctly for all such strings; e.g. "A1" -> false.
Jonik
2009-11-06 12:04:15
@Milli. Curious - on my machine `"11".matches("^([0-9])(?!\\1+$)[0-9]+$")` is false! Java 1.6.0_15.
Jonik
2009-11-06 12:07:11
I used one '\' in the regex as how Tim specified. I should have noticed that. Thanks a bunch Jonik. And a warm thanks to Tim.
Milli
2009-11-06 12:12:05
Ah, right, I didn't even notice that. IntelliJ IDEA fixed it for me automatically when pasting in the regex for testing :)
Jonik
2009-11-06 12:14:58
A:
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
mmorrisson
2009-11-07 00:19:42