Java – how do I replace multiple strings in one line?
•
Java
I want to insert "ob" before each vowel I tried the following code:
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 the above code, it replaces a with oba, but when I replace o with Obo, it replaces o in the original text and O in oba. For example, for "I won't" I want to output "Obi wobon't", but it gives "Obi wobon't", because o in Obi from the first line is regarded as a vowel
I need a solution that won't replace the new o
Solution
Because replaceall uses regular expressions, you can use references to capture elements in the replacement string:
out=out.replaceAll("[AEIoUY]","OB$0");
>[aeiouy] capture a single character from the aeiouy list > replace $0 in the string represents the captured character
This is a demo
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码