6

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.

1 Answers1

8

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Yeah, that's neat. Changing as you suggested Is stringBuilder needed or not? – Saurabh Prajapati Dec 22 '17 at 10:44
  • I don't know what advantage you think `StringBuilder` would confer here. You're doing regex replacement, which isn't supported by `StringBuilder`. Just stick with `String`. – Andy Turner Dec 22 '17 at 10:52