1

特定の文字列の数字を取得したいので、以下のコードを使用しました

String sample = "7011WD";
    String output = "";
    for (int index = 0; index < sample.length(); index++)
    {
        if (Character.isDigit(sample.charAt(index)))
        {
            char aChar = sample.charAt(index);
            output = output + aChar;
        }
    }

    System.out.println("output :" + output);

結果は次のとおりです。 出力:7011

出力を取得する簡単な方法はありますか?

4

2 に答える 2

6

出力を取得する簡単な方法はありますか

正規表現\\D+D数字ではないもの、+1つ以上の出現を意味する)を使用してから、String#replaceAll()すべての非数字を空の文字列で使用できます。

String sample = "7011WD";
String output = sample.replaceAll("\\D+","");

ただし、regex の使用はまったく効率的ではありません。また、この正規表現は小数点も削除します!

プリミティブまたはそれぞれを取得するには、 Integer#parseInt(output)またはLong#parseLong(output)を使用する必要があります。intlong


Google の Guava CharMatcherも使用できます。inRange()を使用して範囲を指定し、 retainFrom() をString使用して、その範囲の文字を順番に返します

于 2013-07-25T04:27:14.710 に答える
1

また、これを行うためにASCIIを使用できます

String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{

        char aChar = sample.charAt(index);
        if(int(aChar)>=48 && int(aChar)<= 57)
        output = output + aChar;
    }
}

System.out.println("output :" + output);
于 2013-07-25T05:01:50.653 に答える