1.replace方法替换字符串中的某一部分字符串
/**
*
* 方法描述 替换指定字符串方法
*
* @param text--字符串
* @param searchString--被替换的字符串
* @param replacement--替换字符串
* @param max 替换字符串searchString的最大个数
* @param ignoreCase 是否忽略大小写
* @return
*
* @author yaomy
* @date 2018年2月6日 下午5:50:28
*/
private static String replace(String text, String searchString, String replacement, int max, boolean ignoreCase)
{
if ((isEmpty(text)) || (isEmpty(searchString)) || (replacement == null) || (max == 0)) {
return text;
}
String searchText = text;
if (ignoreCase) {
searchText = text.toLowerCase();
searchString = searchString.toLowerCase();
}
int start = 0;
int end = searchText.indexOf(searchString, start);
if (end == -1) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= (max > 64 ? 64 : max < 0 ? 16 : max);
StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != -1) {
buf.append(text, start, end).append(replacement);
start = end + replLength;
max--; if (max == 0) {
break;
}
end = searchText.indexOf(searchString, start);
}
buf.append(text, start, text.length());
return buf.toString();
}
2.replace方法替换字符串中指定的字符并且指定替换的个数,区分大小写
public static String replace(String text, String searchString, String replacement, int max)
{
return replace(text, searchString, replacement, max, false);
}
3.replace方法替换字符串中指定的字符串,区分大小写,替换所有匹配到的字符串
public static String replace(String text, String searchString, String replacement)
{
return replace(text, searchString, replacement, -1);
}
4.replace方法替换掉所有正则表达式匹配的字符串
public static String replaceAll(String text, String regex, String replacement)
{
if ((text == null) || (regex == null) || (replacement == null)) {
return text;
}
return text.replaceAll(regex, replacement);
}
5.replaceEach和replaceEachRepeatedly使用数组批量指定要替换的字符串
StringUtils.replaceEach(searchText, new String[] {"ni","ma","yao"}, new String[] {"NI","Ma","LL"})
StringUtils.replaceEachRepeatedly(searchText, new String[] {"ni","ma","yao"}, new String[] {"NI","Ma","LL"})
6.replaceFirst方法替换掉第一个匹配正则表达式的子字符串
public static String replaceFirst(String text, String regex, String replacement)
{
if ((text == null) || (regex == null) || (replacement == null)) {
return text;
}
return text.replaceFirst(regex, replacement);
}
7.replaceOnce方法替换掉字符串的子字符串中匹配到的字符串一次
public static String replaceOnce(String text, String searchString, String replacement)
8.replacePattern方法替换掉与正则表达式匹配的子字符串
public static String replacePattern(String source, String regex, String replacement)
{
if ((source == null) || (regex == null) || (replacement == null)) {
return source;
}
return Pattern.compile(regex, 32).matcher(source).replaceAll(replacement);
}