1

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.

2 Answers 2

2

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").

Sign up to request clarification or add additional context in comments.

1 Comment

+1 you are too fast ... but since he requested "at the end of a word/string" \b is probably the better choice than $
2

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

1 Comment

You are missing an anchor at the end. This regex will find m[abcd] anywhere in the word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.