Java String usuń wszystkie znaki inne niż numeryczne

Próbuje usunąć wszystkie litery i znaki, które nie są 0-9 i Kropka. Używam Character.isDigit() , ale również usuwa dziesiętne, jak Mogę również zachować dziesiętne?

Author: Super Chafouin, 2012-04-29

8 answers

Wypróbuj ten kod:

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

Teraz str będzie zawierać "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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-30 06:26:26

Użyłbym regex.

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

Druki

2367.2723

Możesz zachować - również dla liczb ujemnych.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-29 14:37:30
String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");

Wynik: 0097-557890-999

Jeśli nie potrzebujesz również " - " w łańcuchu, możesz zrobić tak:

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

Wynik: 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-04 23:43:22

Z guawą:

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

Zobacz 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-27 20:52:35

Prosty sposób bez użycia Regex:

Dodanie dodatkowego sprawdzania znaków dla kropki '.' rozwiąże wymóg:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-25 12:40:02

Sposób na zastąpienie go strumieniem 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-15 20:14:12

Separator dziesiętny waluty może się różnić w zależności od lokalizacji. Niebezpieczne może być zawsze rozważenie . jako separatora. tj.

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

Myślę, że właściwą drogą jest:

  • uzyskaj znak dziesiętny przez DecimalFormatSymbols domyślnie lub określony jeden.
  • Cook regex wzór ze znakiem dziesiętnym w celu uzyskania cyfr tylko

A oto jak to rozwiązuję:

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

Kod:

    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;
}

Mam nadzieję, że może pomocy".

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-21 20:54:47