本文介绍了当替换文本与搜索文本重叠时,用Java替换多个子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下字符串:

cat dog fish dog fish cat

你想用狗替换所有 ,所有,以及所有使用。直观地说,预期结果:

You want to replace all cats with dogs, all dogs with fish, and all fish with cats. Intuitively, the expected result:

dog fish cat fish cat dog

如果你尝试使用 replaceAll()循环显而易见的解决方案,你得到:

If you try the obvious solution, looping through with replaceAll(), you get:


  1. (原创)猫狗鱼狗鱼猫

  2. (猫 - >狗)狗狗鱼狗鱼狗

  3. (狗 - >鱼)鱼鱼鱼鱼鱼鱼

  4. (鱼 - >猫)猫猫猫猫猫

  1. (original) cat dog fish dog fish cat
  2. (cat -> dog) dog dog fish dog fish dog
  3. (dog -> fish) fish fish fish fish fish fish
  4. (fish -> cat) cat cat cat cat cat cat

显然,这不是预期的结果。那么最简单的方法是什么?我可以用 Pattern Matcher (还有很多 Pattern.quote)来拼凑一些东西( ) Matcher.quoteReplacement()),但我拒绝相信我是第一个遇到此问题且没有库函数的人解决这个问题。

Clearly, this is not the intended result. So what's the simplest way to do this? I can cobble something together with Pattern and Matcher (and a lot of Pattern.quote() and Matcher.quoteReplacement()), but I refuse to believe I'm the first person to have this problem and there's no library function to solve it.

(FWIW,实际案例有点复杂,不涉及直接掉期。)

(FWIW, the actual case is a bit more complicated and doesn't involve straight swaps.)

推荐答案

似乎可以满足您的需求:

It seems StringUtils.replaceEach in apache commons does what you want:

StringUtils.replaceEach("abcdeab", new String[]{"ab", "cd"}, new String[]{"cd", "ab"});
// returns "cdabecd"

请注意,上述链接中的文档似乎是错误。有关详细信息,请参阅下面的评论。

Note that the documenent at the above links seems to be in error. See comments below for details.

这篇关于当替换文本与搜索文本重叠时,用Java替换多个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 20:52