使用正则表达式替换字符串的结尾

时间:2012-04-19 07:58:58

标签: java regex matching

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

结束:m [abcd]

替换:?q

单词:dfma,ghmc,tdfmd

期望的结果:dfaq,ghcq,tdfdq

如何使用Java中的Strings的replaceAll方法或任何其他Java方法来执行此操作?也许我可以用很多代码来制作它,但我要求更短的解决方案。我不知道如何连接到separete正则表达式。

2 个答案:

答案 0 :(得分: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")。

答案 1 :(得分: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);
相关问题