Saurabh Prajapati
Saurabh Prajapati

Reputation: 332

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.

Upvotes: 6

Views: 742

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

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.

Upvotes: 8

Related Questions