目前替代多個單詞我做最有效的方法使用一個字符串
例子:
line.replaceAll(",","").replaceAll("cat","dog").replaceAll("football","rugby");
我認爲它難看。不確定更好的方法來做到這一點?也許循環通過hashmap?
編輯:
通過效率我的意思是更好的代碼風格和靈活性
目前替代多個單詞我做最有效的方法使用一個字符串
例子:
line.replaceAll(",","").replaceAll("cat","dog").replaceAll("football","rugby");
我認爲它難看。不確定更好的方法來做到這一點?也許循環通過hashmap?
編輯:
通過效率我的意思是更好的代碼風格和靈活性
除此之外,實際更換內部轉換爲regex
,我認爲這種做法是好的。非正則表達式的實現可以在StringUtils.replace(..)中找到。
看看可能存在哪些替代方法,您仍然需要一些東西來識別字符串對。這可能是這樣的:
MultiReplaceUtil.replaceAll{line,
{",", ""}, {"cat", "dog"}, {"football", "rugby"}};
或許
MapReplaceUtil(String s, Map<String, String> replacementMap);
甚至
ArrayReplaceUtil(String s, String[] target, String[] replacement);
均未編碼實踐方面似乎更直觀的給我。
您可以使用Matcher.appendReplacement()
/appendTail()
構建非常靈活的搜索和替換功能。
在JavaDoc的例子是這樣的:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
現在,while
循環中,你可以自己決定什麼樣的替換文本是和底座相匹配的實際內容的信息。
例如,你可以使用模式(,|cat|football)
匹配,
,cat
或football
並決定根據循環內的實際匹配實際更換。
您可以通過這種方式構建更靈活的東西,例如用十六進制數字或類似操作替換所有十進制數字。
這並不是因爲短和簡單爲你的代碼,但你可以建立與它短期和簡單的方法。
此功能已在Commons Lang的StringUtils
類中實現。
StringUtils.replaceEach(String text, String[] searchList, String[] replacementList)
我相信它不是在標準庫,而是在Apache Commons [鏈接]( https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#replaceEach%28java.lang.String,%20java.lang.String [] ,%20java.lang.String []%29) – tkokasih
新版本將是['StrSubstitutor'](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/ commons/text/StrSubstitutor.html)來自[Apache Commons Text](https://commons.apache.org/proper/commons-text/)。 – Andreas
對於斯卡拉愛好者:
"cat".r.replaceAllIn("one cat two cats in the yard", m => "dog")
隨着m
你甚至可以參數化的替代品。
是關於運行時效率的問題嗎?靈活性?代碼風格?請澄清。 – Mac
這也可能是一個正確的問題,因爲在N遍過程中進行的替換可能不等同於在單遍過程中執行N對替換。 – Xion
更新的問題,但尋找代碼風格更好,並允許靈活性 – Decrypter