Provide helper methods to replace a string from multiple replaced strings to multiple substitutes
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringHelper {
/**
* This is test method to replace a string from:
* aaa > zzz
* \t > /t
* \r > /r
* \n > /n
*/
public static void run()
{
String[] replacedStrings = new String[] {"aaa", "\t", "\r", "\n"};
String[] replacements = new String[] {"zzz", "/t", "/r", "/n"};
Pattern pattern = getReplacePattern(replacedStrings);
// The result is "zzza/tb/rc/nd/te/nf"
System.out.println(replace("aaaa\tb\rc\nd\te\nf", pattern, replacedStrings, replacements));
// The result is "zzza/tb/rc/nd/te/nf/r"
System.out.println(replace("aaaa\tb\rc\nd\te\nf\r", pattern, replacedStrings, replacements));
}
/**
* Return a Pattern instance from a specific replaced string array.
* @param replacedStrings replaced strings
* @return a Pattern instance
*/
public static Pattern getReplacePattern(String[] replacedStrings)
{
if (replacedStrings == null || replacedStrings.length == 0) return null;
String regex = "";
for (String replacedString : replacedStrings)
{
if (regex.length() != 0)
{
regex = regex + "|";
}
regex = regex + "(" + replacedString + ")";
}
regex = regex + "";
return Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE);
}
/**
* Replace a string.
* @param value the string.
* @param pattern the Pattern instance.
* @param replacedStrings the replaced string array.
* @param replacements the replacement array.
* @return
*/
public static String replace(String value, Pattern pattern, String[] replacedStrings, String[] replacements)
{
if (pattern == null) return value;
if (replacedStrings == null || replacedStrings.length == 0) return value;
if (replacements == null || replacements.length == 0) return value;
if (replacedStrings.length != replacements.length)
{
throw new RuntimeException("replacedStrings length must same as replacements length.");
}
Matcher matcher = pattern.matcher(value);
StringBuffer buffer = new StringBuffer();
int lastIndex = 0;
while (matcher.find()) {
buffer.append(value.subSequence(lastIndex, matcher.start()));
lastIndex = matcher.end();
String group = matcher.group();
for (int i = 0; i < replacedStrings.length; i++)
{
if (group.equals(replacedStrings[i]))
{
buffer.append(replacements[i]);
break;
}
}
}
buffer.append(value.subSequence(lastIndex, value.length()));
return buffer.toString();
}
}