Most efficient way to use replace multiple words i

2020-01-26 09:54发布

At the moment I'm doing

Example:

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

I think that it ugly. Not sure a better way to do this? Maybe loop through a hashmap?

EDIT:

By efficiency I mean better code style and flexibility

标签: java replace
4条回答
ら.Afraid
2楼-- · 2020-01-26 10:22

For Scala lovers:

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

With m you can even parameterize your replacement.

查看更多
仙女界的扛把子
3楼-- · 2020-01-26 10:33

You can use Matcher.appendReplacement()/appendTail() to build very flexible search-and-replace features.

The example in the JavaDoc looks like this:

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());

Now, inside that while loop you can decide yourself what the replacement text is and base that information on the actual content being matched.

For example you could use the pattern (,|cat|football) to match ,, cat or football and decide on the actual replacement based on the actual match inside the loop.

You can make build even more flexible things this way, such as replacing all decimal numbers with hex numbers or similar operations.

It's not as short and simple as your code, but you can build short and simple methods with it.

查看更多
爷的心禁止访问
4楼-- · 2020-01-26 10:43

This functionality is already implemented in Commons Lang's StringUtils class.

StringUtils.replaceEach(String text, String[] searchList, String[] replacementList)
查看更多
甜甜的少女心
5楼-- · 2020-01-26 10:44

Apart from that the actual replace is internally converted to a regex I think that approach is fine. A non-regex implementation can be found in StringUtils.replace(..) .

Looking at what alternatives there might be, you still need something to identify pairs of strings. This could look like:

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

or perhaps

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

or even

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

neither of which seems more intuitive to me in terms of coding practice.

查看更多
登录 后发表回答