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?
8 answers
Prueba este código:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Ahora str
contendrá "12.334.78"
.
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.
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
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
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+","");
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();
}
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.
}
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,'.
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