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

In scenarios where I use 5-10 replacements, it is 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.

+6
source share
1 answer

Using StringBuilderhere will not help.

A better improvement would be to use a single regex:

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

Here it \\1coincides with what was recorded in the group (one|two|etc).

+8
source

All Articles