1

単語/文字列の末尾を次の式に一致させようとしています: "m[abcd]" そして、この末尾をこの "?q" のような別のものに置き換えます。ここで、疑問符は文字 a のいずれかと一致します。 b、cまたはd。問題は、私には多くの異なるエンディングがあることです。これは例です:

エンディング:m[abcd]

置換:?q

言葉:dfma、ghmc、tdfmd

望ましい結果: dfaq、ghcq、tdfdq

Javaまたは他のJavaメソッドの文字列のreplaceAllメソッドを使用してそれを行う方法は? 多分私はたくさんのコードでそれを作ることができますが、私はより短い解決策を求めています. 別の正規表現に接続する方法がわかりません。

4

2 に答える 2

2

これを行うには、キャプチャ グループを使用できます。例のために。

String pattern = "m([abcd])\\b";  //notice the parantheses around [abcd].
Pattern regex = Pattern.compile(pattern);

Matcher matcher = regex.matcher("dfma");
String str = matcher.replaceAll("$1q");  //$1 represent the captured group
System.out.println(str);

matcher = regex.matcher("ghmc");
str = matcher.replaceAll("$1q");
System.out.println(str);

matcher = regex.matcher("tdfmd");
str = matcher.replaceAll("$1q");
System.out.println(str);
于 2012-04-19T08:10:02.637 に答える
2

文字列に単語全体が含まれていると仮定します。

String resultString = subjectString.replaceAll(
    "(?x)     # Multiline regex:\n" +
    "m        # Match a literal m\n" +
    "(        # Match and capture in backreference no. 1\n" +
    " [a-d]   # One letter from the range a through d\n" +
    ")        # End of capturing group\n" +
    "$        # Assert position at the end of the string", \
    "$1q");   // replace with the contents of group no. 1 + q

文字列に多くの単語が含まれていて、それらすべてを一度に検索/置換したい場合は、stema の提案に従って\\b代わりに使用します (ただし、検索正規表現のみで、置換部分はそのままにしておく必要があります)。$"$1q"

于 2012-04-19T08:01:41.150 に答える