Usando la siguiente expresión regular:
^(\d)(?!\1+$)\d{3}-\d{1}$Funciona para el patrón, pero necesito validar todos los números que no sean iguales incluso después del guión (-).
Ejemplo
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 allowedUsando referencias anteriores , este problema se vuelve bastante fácil (y afortunadamente js regex lo admite).
La expresión regular a continuación coincide solo con las entradas no válidas.
^(\d)\1+-\1$Demostración de expresiones regulares
^ - 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 lineLuego, para el lado JS, si la expresión regular coincide, sabrá que la entrada no es válida.
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') } });EDITAR
Para manejar los nuevos requisitos, puede simplemente o la expresión regular a otra expresión regular comprobando la longitud completa.
^(?:(\d)\1+-\1$|.{7,})Y como parece que estás usando 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"); } } } }** Producción **
0000-0 - INVALID 0000-1 - VALID 1111-1 - INVALID 1234-2 - VALID 1234567-2 - INVALID 1234-26 - INVALID Process finished with exit code 0