Using the following regex:
^(\d)(?!\1+$)\d{3}-\d{1}$
It works for the pattern but I need to validate all numbers not same even after hyphen (-).
Example
0000-0 not allowed (because of all are same digits)
0000-1 allowed
1111-1 not allowed (because of all are same digits)
1234-2 allowed
Using back references, this problem becomes fairly easy (and thankfully js regex supports this).
The regex below matches only the invalid inputs.
^(\d)\1+-\1$
^ - Start of line
(\d) - create a capturing group in the first digit (important for the next part to work)
\1+ - back reference group 1 (\d+) and match it one or more times
- - match a hyphen
\1 - back reference group 1
$ - end of line
Then for the JS side, if the regex matches you know the input was invalid.
const inputs = [
'0000-0',
'0000-1',
'1111-1',
'1234-2'
];
const regex = /^(\d)\1+-\1$/;
inputs.forEach(item => {
if (item.match(regex)) {
console.log(item + ' - INPUT NOT ALLOWED')
} else {
console.log(item + ' - VALID INPUT')
}
});
EDIT
To handle the new requirements, you can just or the regex to another regex checking the entire length.
^(?:(\d)\1+-\1$|.{7,})
And since it sounds like you're using Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// String to be scanned to find the pattern.
String[] lines = {
"0000-0",
"0000-1",
"1111-1",
"1234-2",
"1234567-2",
"1234-26"
};
String pattern = "^(?:(\\d)\\1+-\\1$|.{7,})";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
for(String line : lines) {
System.out.print(line);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println(" - INVALID");
}else {
System.out.println(" - VALID");
}
}
}
}
** Output **
0000-0 - INVALID
0000-1 - VALID
1111-1 - INVALID
1234-2 - VALID
1234567-2 - INVALID
1234-26 - INVALID
Process finished with exit code 0