Nice programing

Java의 문자열에서 숫자가 아닌 문자를 어떻게 제거합니까?

nicepro 2020. 12. 13. 11:08
반응형

Java의 문자열에서 숫자가 아닌 문자를 어떻게 제거합니까?


긴 끈이 있습니다. 숫자를 배열로 분할하는 정규식은 무엇입니까?


제거 또는 분할 중입니까? 이렇게하면 숫자가 아닌 모든 문자가 제거됩니다.

myStr = myStr.replaceAll( "[^\\d]", "" )

문자열에서 숫자가 아닌 모든 문자를 제거하는 또 다른 방법 :

String newString = oldString.replaceAll("[^0-9]", "");

String str= "somestring";
String[] values = str.split("\\D+"); 

또 다른 정규식 솔루션 :

string.replace(/\D/g,'');  //remove the non-Numeric

마찬가지로

string.replace(/\W/g,'');  //remove the non-alphaNumeric

RegEX에서 '\'기호는 뒤에 오는 문자를 템플릿으로 만듭니다. \ w - alphanumeric , \ W - Non-AlphaNumeric 은 문자 대문자로 표시 하면 부정됩니다 .


String 클래스의 Split () 메서드를 사용하고 적어도 하나의 숫자가 아닌 것과 일치하는 "\ D +"의 정규식을 전달하려고합니다.

myString.split("\\D+");

Java 8 컬렉션 스트림 :

StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());

이것은 Flex SDK 4.14.0에서 작동합니다.

myString.replace (/ [^ 0-9 && ^.] / g, "");


아래와 같은 재귀 방법을 사용할 수 있습니다.

public static String getAllNumbersFromString(String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        char c = input.charAt(input.length() - 1);
        String newinput = input.substring(0, input.length() - 1);

            if (c >= '0' && c<= '9') {
            return getAllNumbersFromString(newinput) + c;

        } else {
            return getAllNumbersFromString(newinput);
        }
    } 

Regex를 사용하지 않는 간단한 방법 :

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)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

이전 답변은 소수점을 제거합니다. Decima l 저장하려면 다음 을 원할 수 있습니다.

String str = "My values are : 900.00, 700.00, 650.50";

String[] values = str.split("[^\\d.?\\d]"); 
//    split on wherever they are not digits ( but don't split digits embedded with decimal point ) 

참고 URL : https://stackoverflow.com/questions/1533659/how-do-i-remove-the-non-numeric-character-from-a-string-in-java

반응형