Search code examples
javastringreplace

Search and Replace in a string with multiple phrases at once


I would like to replace this code with a more efficient one:

String s = "The brown fox is jumping over a fence";
s = s.replace(s, "brown", "black");
s = s.replace(s, "fox", "dog");
s = s.replace(s, "fence", "pond");
System.out.println(s);

The above code is running though the long text 3 times and creating new strings every time. Is there some library that can do the same job with only one iteration through the long text.

I would use StringBuilder, go through the text char by char and try to find one of the search phrases and then try to efficiently create a new text.

But I don't want to implement myself, I'm looking for a already existing library method for this. (Apache, Google, ....)

Thank you.


Solution

  • If you really wanted to make only one pass through the string, you could do a regex search on an alternation, then selectively do replacements based on each particular match. For example:

    String s = "The brown fox is jumping over a fence";
    String pattern = "\\b(?:brown|fox|fence)\\b";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(s);
    StringBuffer buffer = new StringBuffer();
    
    while (m.find()) {
        switch (m.group()) {
            case "brown":
                m.appendReplacement(buffer, "black");
                break;
            case "fox":
                m.appendReplacement(buffer, "dog");
                break;
            case "fence":
                m.appendReplacement(buffer, "pond");
                break;
        }
    }
    
    m.appendTail(buffer);
    
    System.out.println(buffer.toString());    // The black dog is jumping over a pond
    

    The above code is very verbose, but if you were doing this replacement on on a very large text (think 100+MB to GB size), then there could be a performance boost by simply making one pass over the text, rather than separate passes for each search term.