Java - 用StringUtils.replaceEach 替換字串裡"所有"的字 (也可以用於將關鍵字反白)
套件:Apache Commons Lang 3.0.1 [Java 5.0+]
網站:http://commons.apache.org/lang/
下載:http://apache.stu.edu.tw//commons/lang/binaries/commons-lang3-3.0.1-bin.zip
範例:
// 本文
String text = "台灣是位於亞洲東部、太平洋西北側的島嶼,面積約3.6萬平方公里。台灣是由歐亞大陸板塊、沖繩板塊和菲律賓海板塊擠壓而隆起的島嶼";
// 想要替換掉的字串
String[] searchList = {"台灣"};
// 新字串(加入HTML tage將「台灣」替換成「反白的台灣」)
String [] replacementList = {"<font style='color:black;background-color: yellow'>" + 台灣 + "</font>"};
// 執行
String rval = StringUtils.replaceEach(str, searchList, replacementList);
輸出:
台灣是位於亞洲東部、太平洋西北側的島嶼,面積約3.6萬平方公里。台灣是由歐亞大陸板塊、沖繩板塊和菲律賓海板塊擠壓而隆起的島嶼
=============================================
官方Java DOC
replaceEach
public static String replaceEach(String text, String[] searchList, String[] replacementList)
-
Replaces all occurrences of Strings within another String.
A
null
reference passed to this method is a no-op, or if any "search string" or "string to replace" is null, that replace will be ignored. This will not repeat. For repeating replaces, call the overloaded method.StringUtils.replaceEach(null, *, *) = null StringUtils.replaceEach("", *, *) = "" StringUtils.replaceEach("aba", null, null) = "aba" StringUtils.replaceEach("aba", new String[0], null) = "aba" StringUtils.replaceEach("aba", null, new String[0]) = "aba" StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba" StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b" StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba" StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte" (example of how it does not repeat) StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
- Parameters:
text
- text to search and replace in, no-op if nullsearchList
- the Strings to search for, no-op if nullreplacementList
- the Strings to replace them with, no-op if null- Returns:
- the text with any replacements processed,
null
if null String input - Throws:
IndexOutOfBoundsException
- if the lengths of the arrays are not the same (null is ok, and/or size 0)- Since:
- 2.4
=============================================
Commons Lang