开发者

Most efficient way to use replace multiple words in a string [duplicate]

开发者 https://www.devze.com 2023-04-10 14:44 出处:网络
This question already has answers here: Java Replacing multiple different substring in a string at once (or in the most efficient way)
This question already has answers here: Java Replacing multiple different substring in a string at once (or in the most efficient way) (11 answers) Closed 6 years ago.

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 开发者_如何学Ca hashmap?

EDIT:

By efficiency I mean better code style and flexibility


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

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


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.


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.


For Scala lovers:

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

With m you can even parameterize your replacement.

0

精彩评论

暂无评论...
验证码 换一张
取 消