fork(1) download
  1. /*
  2.   Eliminar de una cadena en java todos los caracteres que no estén dentro del patrón
  3.   https://es.stackoverflow.com/q/113684/127
  4. */
  5.  
  6. class Ideone
  7. {
  8. public static String soloNumFree (String texto) {
  9. String patron = "\\d+(?:[.,]\\d+)*|Free";
  10. String regex = String.format("(?:(?!%s)(?s:.))*(%s)?", patron, patron);
  11.  
  12. return texto.replaceAll(regex, "$1");
  13. }
  14.  
  15.  
  16. public static void main (String[] args) throws java.lang.Exception
  17. {
  18. //Pruebas
  19. String[] pruebas = {
  20. "AU$26.95 с уч. GST",
  21. "Free с уч. GST",
  22. "#$%&/=123,456,789.01xxxFree Free!!! 3:)"
  23. };
  24.  
  25. for (String prueba: pruebas) {
  26. String resultado = soloNumFree(prueba);
  27. System.out.printf("%-40s --> '%s'%n", prueba, resultado);
  28. }
  29. }
  30. }
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
AU$26.95 с уч. GST                       --> '26.95'
Free с уч. GST                           --> 'Free'
#$%&/=123,456,789.01xxxFree Free!!! 3:)  --> '123,456,789.01FreeFree3'