Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.replace() or StringBuilder.replace()

In scenarios where I am using 5-10 replacements is it necessary to use stringbuilder.

String someData = "......";
someData = someData.replaceAll("(?s)<tag_one>.*?</tag_one>", "");
someData = someData.replaceAll("(?s)<tag_two>.*?</tag_two>", "");
someData = someData.replaceAll("(?s)<tag_three>.*?</tag_three>", "");
someData = someData.replaceAll("(?s)<tag_four>.*?</tag_four>", "");
someData = someData.replaceAll("(?s)<tag_five>.*?</tag_five>", "");
someData = someData.replaceAll("<tag_five/>", "");
someData = someData.replaceAll("\\s+", "");

Will it make a difference if I use stringBuilder Here.

like image 985
Saurabh Prajapati Avatar asked Dec 22 '17 10:12

Saurabh Prajapati


People also ask

What is the difference between Replace () and replaceAll ()?

The replaceAll() method is similar to the String. replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string.

What does replace () do in Java?

Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

How do you replace a StringBuilder?

StringBuilder replace() in Java with Examples The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String.

Does Java string replace replace all?

String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex. There are two overloaded methods available in Java for replace() : String.


1 Answers

Using StringBuilder won't make a useful difference here.

A better improvement would be to use a single regex:

someData = someData.replaceAll("(?s)<tag_(one|two|three|four|five)>.*?</tag_\\1>", "");

Here, the \\1 matches the same thing that was captured in the (one|two|etc) group.

like image 70
Andy Turner Avatar answered Oct 11 '22 21:10

Andy Turner