Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a specific string in Java?

I usually don't ask for help but here I really need it.
I have the following code example:

String text = "aa aab aa aab";
text = text.replace("aa", "--");
System.out.println(text);

Console output: -- --b -- --b

I have a question, how do I only replace aa parts of the string not aab included.
So the console output is:

-- aab -- aab

I have another example:

String text = "111111111 1";
text = text.replace("1", "-");
System.out.println(text);

Console output: --------- -

I only want to replace a single character, not all the same ones who are placed together.
So the console output is:

111111111 -

Are there any Java shortcuts for situations like these? I can't figure it out, how to only replace specific part of the string.
Any help would be appreciated :)

like image 377
Michael Avatar asked Mar 12 '26 09:03

Michael


1 Answers

You could use a regular expression with String.replaceAll(String, String). By using word boundaries (\b), something like

String[] texts = { "aa aab aa aab", "111111111 1" };
String[] toReplace = { "aa", "1" };
String[] toReplaceWith = { "--", "-" };
for (int i = 0; i < texts.length; i++) {
    String text = texts[i];
    text = text.replaceAll("\\b" + toReplace[i] + "\\b", toReplaceWith[i]);
    System.out.println(text);
}

Outputs (as requested)

-- aab -- aab
111111111 -
like image 64
Elliott Frisch Avatar answered Mar 14 '26 22:03

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!