How to replace character in the string using regex in java?

Ruddy Cahyanto :

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?

anubhava :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328651&siteId=1