Here you can find the source of replace(String source, String[] patterns, String[] replacements)
Parameter | Description |
---|---|
patterns | an array of regexes of what to find and what will be replaced. Note, that since they are regexes, you must be sure to escape special regex tokens. |
public static final String replace(String source, String[] patterns, String[] replacements)
//package com.java2s; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /**//from ww w . j a v a 2s. co m * Search source for instances of patterns from patterns[]. If found, replace * with the corresponding replacement in replacements[] (i.e., pattern[n] is replaced by * replacement[n]) * * @param patterns an array of regexes of what to find and what will be replaced. Note, that since they are * regexes, you must be sure to escape special regex tokens. */ public static final String replace(String source, String[] patterns, String[] replacements) { if (source == null) return null; StringBuffer buf = new StringBuffer(); for (int i = 0; i < patterns.length; ++i) { if (i != 0) buf.append("|"); buf.append("(").append(patterns[i]).append(")"); } String regexString = buf.toString(); Pattern regex = Pattern.compile(regexString); Matcher m = regex.matcher(source); if (m.groupCount() != replacements.length) throw new IllegalArgumentException("Mismatch between pattern and replacements array"); StringBuffer result = null; int idx = 0; while (m.find()) { if (result == null) result = new StringBuffer(source.length() + 32); result.append(source.substring(idx, m.start())); for (int i = 0; i < replacements.length; ++i) { // the 0th group is the entire expression if (m.group(i + 1) != null) { result.append(replacements[i]); idx = m.end(); break; } } } if (result == null) return source; result.append(source.substring(idx)); return result.toString(); } }