fork download
  1. /* Obtener el texto que coincide con un número al inicio del texto
  2.   https://es.stackoverflow.com/q/71535/127 */
  3.  
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. class Ideone
  8. {
  9. private static void filtraNumeros(String texto){
  10.  
  11. String regex = "^\\d{1,12}(\\.\\d{1,3})?";
  12.  
  13. Pattern patron = Pattern.compile(regex);
  14. Matcher matcher = patron.matcher(texto);
  15.  
  16. if (matcher.find()) {
  17. //Imprimir todo el texto con el que se coincidió
  18. System.out.println( "Número: " + matcher.group());
  19. //Imprimir sólo el punto y los decimales (si tiene)
  20. if (matcher.group(1) != null) {
  21. System.out.println( "Decimales: " + matcher.group(1) );
  22. }
  23. } else {
  24. System.out.println( "No empieza con un número" );
  25. }
  26. }
  27.  
  28. public static void main (String[] args) throws java.lang.Exception
  29. {
  30. // Prueba
  31. String prueba ="123.45678 etc.";
  32. filtraNumeros(prueba);
  33. }
  34. }
Success #stdin #stdout 0.07s 2841600KB
stdin
Standard input is empty
stdout
Número: 123.456
Decimales: .456