HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Replacing multiple search strings simultaneously

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
searchsimultaneouslyreplacingmultiplestrings

Problem

A utility method StringUtils.replace to replace multiple search strings simultaneously.
I'm looking for a review of any and all aspects, but especially:

  • Is there's a better way to do this? (short of external libraries)



  • Is the parameter validation OK the way I did?



  • Is the way I test adequate and up to good practices in testing?



The code:

```
import java.util.*;
import java.util.stream.Stream;

public class StringUtils {

public static final String ERR_NULL_PARAM = "none of the parameters should be null";
public static final String ERR_SEARCHSTRINGS_REPLACEMENTS_LENGTH_MISMATCH =
"there must be the same number of search strings and replacements";
public static final String ERR_NULL_OR_EMPTY_SEARCHSTRING = "there must be no null element or empty search string";
public static final String ERR_NULL_REPLACEMENT = "there must be no null element in replacements";
public static final String ERR_DUPLICATE_SEARCHSTRINGS = "search strings must be distinct";

/**
* Replace multiple search strings simultaneously
*
* @param text the source text
* @param searchStrings search strings to replace
* @param replacements texts to replace the corresponding search strings
* @return new text with search strings replaced
*/
public static String replace(String text, String[] searchStrings, String[] replacements) {
validateParams(text, searchStrings, replacements);

StringBuffer buffer = new StringBuffer();
Pattern pattern = Pattern.compile(Stream.of(searchStrings).collect(joining("|")));
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String match = matcher.group();
for (int i = 0; i x == null || x.isEmpty());
}

private static boolean anyNull(String[] strings) {
return Stream.of(strings).allMatch(x -> x == null);
}

private static boolean containsDuplicates(String[] strings) {
return Stream.o

Solution

This is a StringUtils class, not RegexUtils. Therefore, I would expect all of the searchStrings to be taken literally. You must quote each of the searchStrings when composing your regex.

For figuring out which replacement string goes with which search string, it might be better to use a HashMap instead of a linear search.

Context

StackExchange Code Review Q#115943, answer score: 4

Revisions (0)

No revisions yet.