mjekov
mjekov

Reputation: 682

Replacing end of string using regular expression

I'm trying to match an end of a word/string with the following expression: "m[abcd]" and replace this ending with another one looking like this "?q", where the question mark matches one of the characters a,b,c or d. The problem is, i have a lot of diffrent endings. This is an example:

Ending: m[abcd]

Replacment: ?q

Words: dfma, ghmc, tdfmd

Desired result: dfaq, ghcq, tdfdq

How to do it using the replaceAll method for Strings in Java or any other Java method? Maybe i can make it with lots of code, but i'm asking for a shorter solution. I don't know how to connect to separete regular expressions.

Upvotes: 1

Views: 6021

Answers (2)

Rahul
Rahul

Reputation: 13056

You can use a capturing group to do this. For ex.

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);

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336238

Assuming your string contains the entire word:

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

If your string contains many words, and you want to find/replace all of them at once, then use \\b instead of $ as per stema's suggestion (but only in the search regex; the replacement part needs to remain as "$1q").

Upvotes: 2

Related Questions