Aka
Aka

Reputation: 171

String replace for some pattern to some pattern

I have a huge String where i need to replace

Pattern A to pattern B
Pattern C to Pattern D
pattern E to pattern F

like 5 or 6 time i have to replace some part of the string.

If i do a direct string operation to replace those one by one, it takes huge Heap space.

Like replaceAll().replaceAll().replaceALL

pattern.compile("(pattern a|patternc)"); wont he me bcoz we can only replace this types of pattern with 1 parrten x.

What could be a memory efficient way to do this replacement.

Does regex have any way to accomplish this?

Upvotes: 0

Views: 258

Answers (1)

1054211
1054211

Reputation: 442

I usually trust apache and they have what you need, but I can't comment on memory efficiency of their implementation of the multiple string replaces

Apache StringUtils.ReplaceEachRepeatedly

From looking at the source code it seem to use StringBuffer manipulation with recursive calls, so it should be somewhat memory efficient (I don't think you will run out of stack space)

Linky to the source code to the Apache's ReplaceEach

EDIT: Apache Commons Lang version 3 actually uses StringBuilder and is trying to minimize memory usage during string replacement. I strongly suggest you look at the source code or use the library directly.

Upvotes: 1

Related Questions