fork download
  1. /*
  2. Java Split excluyendo rango
  3. https://es.stackoverflow.com/q/138135/127
  4. */
  5.  
  6. import java.io.*;import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. final String regex = "(\\d+)(?:\\[(\\d+)Y,(\\d+)W,(\\d+)H])?";
  15. final String texto = "1,2,3,20[4Y,2W,4H] , 10[2Y,1W,5H],4 , 5[10Y,20W,5H]";
  16.  
  17. // así se compila siempre un regex
  18. final Pattern pattern = Pattern.compile(regex);
  19. final Matcher matcher = pattern.matcher(texto);
  20.  
  21. //y así se buscan siempre todas las coincidencias
  22. while (matcher.find()) {
  23. //asignamos el valor capturado por cada grupo
  24. String valor = matcher.group(1);
  25. String rangoY = matcher.group(2);
  26. String rangoW = matcher.group(3);
  27. String rangoH = matcher.group(4);
  28.  
  29. //imprimimos en consola
  30. System.out.printf("Valor: %3s - Y: %4s - W: %4s - H: %4s%n",valor,rangoY,rangoW,rangoH);
  31. }
  32. }
  33. }
Success #stdin #stdout 0.1s 28148KB
stdin
Standard input is empty
stdout
Valor:   1 - Y: null - W: null - H: null
Valor:   2 - Y: null - W: null - H: null
Valor:   3 - Y: null - W: null - H: null
Valor:  20 - Y:    4 - W:    2 - H:    4
Valor:  10 - Y:    2 - W:    1 - H:    5
Valor:   4 - Y: null - W: null - H: null
Valor:   5 - Y:   10 - W:   20 - H:    5