0

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?

2
  • Use StringBuilder instead if you want to modify your string a large number of times. Commented Nov 29, 2012 at 21:02
  • "it takes huge Heap space." Do you know exactly how much space? Commented Nov 29, 2012 at 21:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

StringUtils.ReplaceEachRepeatedly function I cant use bcoz it looks like the method cant handle regex. It only consider String[] public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList)
May be if you could provide with samples of patterns you are using to search and the pattern you are using for replacement we would be able to answer better. I especially don't understand the part where you say you want a replacement pattern. Can you elaborate on what the replacement patter is when you say Pattern A to Pattern B? Regexp is not something you want to use lightly, it's very powerful and could also be very resource consuming. There are scripting languages build around regex, you may want to use AWK for the pre-processing instead of java.
Also please consider using regex grouping and backreferencing as the strategy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.