2011-10-05 18 views
24

目前替代多个单词我做最有效的方法使用一个字符串

例子:

line.replaceAll(",","").replaceAll("cat","dog").replaceAll("football","rugby"); 

我认为它难看。不确定更好的方法来做到这一点?也许循环通过hashmap?

编辑:

通过效率我的意思是更好的代码风格和灵活性

+3

是关于运行时效率的问题吗?灵活性?代码风格?请澄清。 – Mac

+2

这也可能是一个正确的问题,因为在N遍过程中进行的替换可能不等同于在单遍过程中执行N对替换。 – Xion

+2

更新的问题,但寻找代码风格更好,并允许灵活性 – Decrypter

回答

4

除此之外,实际更换内部转换为regex,我认为这种做法是好的。非正则表达式的实现可以在StringUtils.replace(..)中找到。

看看可能存在哪些替代方法,您仍然需要一些东西来识别字符串对。这可能是这样的:

MultiReplaceUtil.replaceAll{line, 
     {",", ""}, {"cat", "dog"}, {"football", "rugby"}}; 

或许

MapReplaceUtil(String s, Map<String, String> replacementMap); 

甚至

ArrayReplaceUtil(String s, String[] target, String[] replacement); 

均未编码实践方面似乎更直观的给我。

20

您可以使用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)匹配,catfootball并决定根据循环内的实际匹配实际更换。

您可以通过这种方式构建更灵活的东西,例如用十六进制数字或类似操作替换所有十进制数字。

这并不是因为简单为你的代码,但你可以建立与它短期和简单的方法。

21

此功能已在Commons LangStringUtils类中实现。

StringUtils.replaceEach(String text, String[] searchList, String[] replacementList) 
+1

我相信它不是在标准库,而是在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

+0

新版本将是['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

1

对于斯卡拉爱好者:

"cat".r.replaceAllIn("one cat two cats in the yard", m => "dog") 

随着m你甚至可以参数化的替代品。

相关问题