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

Saurabh Prajapati :

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.

Andy Turner :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=468082&siteId=1
Recommended