1

I want to replace every x in the end of line or string and behind every letters except aiueo with nya. Expected input and output:

Input: bapakx

Output: bapaknya

I've tried this one:

String myString = "bapakx";
String regex = "[^aiueo]x(\\s|$)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(myString);
if(m.find()){
    myString = m.replaceAll("nya");
}

But the output is not bapaknya but bapanya. The k character is also replaced. How can I solve this?

1 Answer 1

3

To get consonant back Use a zero width lookbehind in your regex as:

String regex = "(?<=[^aiueo])x(?=\\s|$)";

Here (?<=[^aiueo]) will only assert presence of consonant before x but won't match it.

Alternatively you can use capture groups:

String regex = "([^aiueo])x(\\s|$)";

and use it as:

myString = m.replaceAll("$1nya");
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, got it. Thank you

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.