Ver Mensaje Individual
  #4 (permalink)  
Antiguo 14/05/2013, 20:28
Avatar de razpeitia
razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 2 meses
Puntos: 1360
Respuesta: Separar cadena String y poner un par de requisitos.

Con un guion solo y ahora limitado a a-zA-Z

Código Java:
Ver original
  1. import java.util.regex.Pattern;
  2. import java.util.regex.Matcher;
  3.  
  4.  
  5. public class Utils {
  6.  
  7.     public static void main(String[] args) {
  8.         String[] tests = new String[]{"ab", "ab1", "ab1-", "2a-b", "321321-asdfasdf-a-46546", ">?<", null, "222-22"};
  9.         for(String test : tests) {
  10.             System.out.println(test + " " + is_valid(test));
  11.         }
  12.     }
  13.  
  14.     public static boolean is_valid(String code) {
  15.  
  16.         if(code == null) return false;
  17.         Pattern p;
  18.         Matcher m;
  19.  
  20.         p = Pattern.compile("-");
  21.         m = p.matcher(code);
  22.         int count = 0;
  23.         while (m.find()) count++;
  24.         if(count != 1) return false;
  25.  
  26.         p = Pattern.compile("\\d");
  27.         m = p.matcher(code);
  28.         if(!m.find()) return false;
  29.  
  30.  
  31.         p = Pattern.compile("[a-zA-Z](.*)[a-zA-Z]");
  32.         m = p.matcher(code);
  33.         if(!m.find()) return false;
  34.  
  35.  
  36.         return true;
  37.     }
  38. }