1

文字列が「abcd」で始まり、その後に 1 ~ 5 桁、次にカンマが続き、0 ~ 3 桁で終わるかどうかを確認する必要があります。

    Pattern pattern = Pattern.compile("abcd[0-9]{1,5},[0-9]{0,3}$");

    String[] data = { "pqrsabcd12345,5", "abcd1234,5", "abcd1234542155,",
            "abcdSD12345,555", "abcd123,555", "abcd12,5555",
            "abcd,5555ffdfd", "abcd2,5555ffdfd", "abcd2,5" };
    for (CharSequence input : data) {
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            System.out.format("\nI found the text  %s :"
                    + " \"%s\" starting at "
                    + "index %d and ending at index %d.%n", input,
                    matcher.group(), matcher.start(), matcher.end());
        }
    }

出力 :

I found the text  pqrsabcd12345,5 : "abcd12345,5" starting at index 4 and ending at index 15.

I found the text  abcd1234,5 : "abcd1234,5" starting at index 0 and ending at index 10.

I found the text  abcd123,555 : "abcd123,555" starting at index 0 and ending at index 11.

I found the text  abcd2,5 : "abcd2,5" starting at index 0 and ending at index 7.

これを使用して、パーツで端を確保できました。のような文字列を停止する必要があると思います"pqrsabcd12345,5"

何か見逃した場合はお知らせください。

4

1 に答える 1

4

正規表現を少し変更するだけです: -

"^abcd[0-9]{1,5},[0-9]{0,3}$"

キャレットを使用するのを忘れました-^文字列の先頭でパターンが一致することを確認します。

または、パターンを最後に一致させたい場合は、メソッドMatcher#matches()の代わりに使用することもできます。Matcher#find()そうすれば、 を使用する必要がなくなりますanchors

matches()したがって、との違いはfind()、要件を満たさない文字列で簡単に表示できます。

// pattern is the reference you are having
pattern.matcher("pqrsabcd12345,5").find(); // Will return true
pattern.matcher("pqrsabcd12345,5").matches(); // Will return false
于 2012-12-23T16:13:32.830 に答える