fork download
  1. /*
  2. Separar expresión matemática con expresiones regulares en Java
  3. https://es.stackoverflow.com/q/127195/127
  4. */
  5.  
  6. import java.util.regex.Pattern;
  7. import java.util.regex.Matcher;
  8.  
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. //variables
  14. final String texto = "1000000.315+5.8/(6.0+1-8*2.0)";
  15. //variables para el regex
  16. final String regex = "([\\d.]+)|[-+*/()]";
  17. final Pattern pattern = Pattern.compile(regex);
  18. final Matcher matcher = pattern.matcher(texto);
  19.  
  20. //buscamos todas las coincidencias
  21. while (matcher.find())
  22. {
  23. if (matcher.group(1) != null) //si se capturó algo en el grupo 1 (el primer conjunto de paréntesis)
  24. {
  25. System.out.println("Número: " + matcher.group());
  26. }
  27. else
  28. {
  29. System.out.println("Símbolo: " + matcher.group());
  30. }
  31. }
  32. }
  33. }
Success #stdin #stdout 0.09s 27944KB
stdin
Standard input is empty
stdout
Número:  1000000.315
Símbolo: +
Número:  5.8
Símbolo: /
Símbolo: (
Número:  6.0
Símbolo: +
Número:  1
Símbolo: -
Número:  8
Símbolo: *
Número:  2.0
Símbolo: )