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?
asked Oct 21, 2019 at 15:47
Ruddy Cahyanto
1131 silver badge7 bronze badges
1 Answer 1
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("1ドルnya");
answered Oct 21, 2019 at 15:50
anubhava
791k67 gold badges604 silver badges671 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ruddy Cahyanto
Ahh, got it. Thank you
lang-java