Search code examples
javaregexstringreplaceall

Multiple uses of replaceAll() String method


I am doing some text preprocessing and I am using the replaceAll() method at least 10 times. This is starting to get inefficient I am afraid.

My code is like:

text = text.replaceAll(regex1, "rStr");
text = text.replaceAll(regex2, "rStr2");
.
.
.
text = text.replaceAll(regexn, "rStrn");

I thought I'd use StringBuilder in order to avoid making new strings all the time, but I didn't notice much difference.

StringBuilder sb = new StringBuilder();
sb.append(text.replaceAll(regex1, "rStr"));
sb.replace(0, sb.length(), sb.toString().replaceAll(regex2, "rStr2"));
.
.
.
sb.replace(0, sb.length(), sb.toString().replaceAll(regexn, "rStrn"));

Any ideas how to make this code more efficient?


Solution

  • Depending on your patterns, you can get decent improvements from precompiling them. replaceAll has to do something like Pattern.compile(patternStr).matcher(this).replaceAll(replacement). It doesn't cache the Pattern, so if you compile it just once, you'll see improvements, provided that code gets called more than once.

    If you can, use String.replace() rather than String.replaceAll(), but it sounds a bit like you need the pattern.