1

我正在尝试将单词/字符串的结尾与以下表达式匹配:“m [abcd]”并将其替换为另一个看起来像“?q”的结尾,其中问号匹配字符之一, b、c 或 d。问题是,我有很多不同的结局。这是一个例子:

结尾:m[abcd]

替换:?q

词:dfma、ghmc、tdfmd

期望的结果:dfaq、ghcq、tdfdq

如何使用 Java 中的字符串的 replaceAll 方法或任何其他 Java 方法来做到这一点?也许我可以用很多代码来完成它,但我要求一个更短的解决方案。我不知道如何连接到单独的正则表达式。

4

2 回答 2

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 回答
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 回答