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?

asked Oct 21, 2019 at 15:47

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("1ドルnya");
answered Oct 21, 2019 at 15:50
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, got it. Thank you

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.