Search code examples
javaregexreplaceall

How to replace more than a string in one line?


I want to insert "OB" before every vowel. I have tried the code below:

String out=txt.toUpperCase();

out=out.replaceAll("A","OBA");
out=out.replaceAll("E","OBE");
out=out.replaceAll("I","OBI");
out=out.replaceAll("O","OBO");
out=out.replaceAll("U","OBU");
out=out.replaceAll("Y","OBY");

When I use that code above, it replaces A with OBA, but then when it comes to replacing O to OBO it replaces the O from the original text and also the O in OBA. For example, for "I WON'T" I want the output "OBI WOBON'T", but instead it gives "OBOBI WOBON'T" as the O from OBI from the first line has been treated as a vowel.

I need a solution which doesn't replace the new O from the encryption.


Solution

  • Since replaceAll takes regex, you can use references to captured elements in your replacement string:

    out=out.replaceAll("[AEIOUY]", "OB$0");
    
    • [AEIOUY] captures a single character from the AEIOUY list
    • $0 in the replacement string stands for the character that has been captured.

    Here is a demo.