Cadena Java eliminar todos los caracteres no numéricos


Tratando de eliminar todas las letras y caracteres que no son 0-9 y un punto. Estoy usando Character.isDigit() pero también elimina el decimal, ¿cómo puedo también mantener el decimal?

Author: Super Chafouin, 2012-04-29

8 answers

Prueba este código:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");

Ahora str contendrá "12.334.78".

 415
Author: Óscar López,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-30 06:26:26

Usaría una expresión regular.

String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);

Imprime

2367.2723

Es posible que desee mantener - también para los números negativos.

 83
Author: Peter Lawrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-29 14:37:30
String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");

Resultado: 0097-557890-999

Si tampoco necesita " - " en Cadena, puede hacer lo siguiente:

String phoneNumberstr = "Tel: 00971-55 7890 999";      
String numberRefined = phoneNumberstr.replaceAll("[^0-9]", "");

Resultado: 0097557890999

 29
Author: Faakhir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-04 23:43:22

Con guayaba:

String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);

Véase http://code.google.com/p/guava-libraries/wiki/StringsExplained

 18
Author: Kerem Baydoğan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 11:41:05
str = str.replaceAll("\\D+","");
 13
Author: Angoranator777,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-27 20:52:35

Forma sencilla sin usar expresiones regulares:

Agregar una comprobación de caracteres adicional para dot '.' resolverá el requisito:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c) || c == '.') {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}
 5
Author: shridutt kothari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 12:40:02

Una forma de reemplazarlo con una corriente java 8:

public static void main(String[] args) throws IOException
{
    String test = "ab19198zxncvl1308j10923.";
    StringBuilder result = new StringBuilder();

    test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );

    System.out.println( result ); //returns 19198.130810923.
}
 1
Author: Orin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-15 20:14:12

El separador decimal de moneda puede ser diferente de la configuración regional a otra. Podría ser peligroso considerar siempre . como separador. es decir,

╔════════════════╦═══════════════════╗
║    Currency    ║      Sample       ║
╠════════════════╬═══════════════════╣
║ USA            ║ $1,222,333.44 USD ║
║ United Kingdom ║ £1.222.333,44 GBP ║
║ European       ║ €1.333.333,44 EUR ║
╚════════════════╩═══════════════════╝

Creo que la manera correcta es:

  • Obtiene el carácter decimal a través de DecimalFormatSymbols por configuración regional predeterminada o especificado uno.
  • Cocine el patrón de expresiones regulares con carácter decimal para obtener solo dígitos

Y aquí cómo lo estoy resolviendo:

import java.text.DecimalFormatSymbols;
import java.util.Locale;

Código:

    public static String getDigit(String quote, Locale locale) {
    char decimalSeparator;
    if (locale == null) {
        decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
    } else {
        decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
    }

    String regex = "[^0-9" + decimalSeparator + "]";
    String valueOnlyDigit = quote.replaceAll(regex, "");
    try {
        return valueOnlyDigit;
    } catch (ArithmeticException | NumberFormatException e) {
        Log.e(TAG, "Error in getMoneyAsDecimal", e);
        return null;
    }
    return null;
}

Espero que pueda ayudar,'.

 1
Author: Maher Abuthraa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-21 20:54:47