Ruddy Cahyanto
Ruddy Cahyanto

Reputation: 113

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

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?

Upvotes: 1

Views: 129

Answers (1)

anubhava
anubhava

Reputation: 786349

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

Upvotes: 3

Related Questions