2

JavaのreplaceAllメソッドについて質問です。
以下のコードでreplaceAllを使い、大文字のAと小文字のaを両方含めBに変換したいのですが、
以下のコードだと大文字のAだけがreplaceAllに反応してしまい、小文字のaが反応しません。
replaceAllで大文字小文字区別せずに検出するには、どのようなコードを書けばいいでしょうか?
equalsと同じようにreplaceAll.IgnoreCaseなども試してみましたが、cannnot find symbolとエラーが出てきてしまいます。


現状のコード:

public class Main{
    public static void main (String args[]){
        String str = "AaBbCc";
        String afterStr = str.replaceAll("A","B"); //ここで本来なら大文字小文字区別せずに出力する
        System.out.println(afterStr);
    }
}

2 件の回答 2

2
    String afterStr = str.replaceAll("(?i)a","B");

CASE_INSENSITIVE

public static final int CASE_INSENSITIVE

Enables case-insensitive matching.

By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched. Unicode-aware case-insensitive matching can be enabled by specifying the UNICODE_CASE flag in conjunction with this flag.

Case-insensitive matching can also be enabled via the embedded flag expression (?i).

0

大文字のAと小文字のaを両方含めBに変換したいのであれば、

String afterStr = str.replaceAll("A","B");

String afterStr = str.replaceAll("[Aa]","B"); 

に変えればAとaがBに置換できます。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。