By utilizing back references, solving this issue becomes quite simple (and fortunately, js regex supports this).
The following regex only identifies the invalid inputs.
^(\d)\1+-\1$
See Regex Demo
^ - Start of line
(\d) - create a capturing group with the first digit (essential for the next step)
\1+ - back reference to group 1 (\d+) and match it one or more times
- - match a hyphen
\1 - back reference to group 1
$ - end of line
On the JS side, if the regex matches, then you can determine that 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')
}
});
Check JS Demo
EDIT
To accommodate the new requirements, simply combine the regex with another regex checking the total length.
^(?:(\d)\1+-\1$|.{7,})
See Demo
And if you are working with 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