Java String.replaceFirst() 接受“起始于”参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2329589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:38:23  来源:igfitidea点击:

Java String.replaceFirst() that takes a "starting from" argument

javaregexstringreplace

提问by Slavko

I need to replace a word in a string looking like "duh duh something else duh". I only need to replace the second "duh", but the first and the last ones need to stay untouched, so replace() and replaceFirst() don't work. Is there a method like replaceFirst(String regex, String replacement, int offset) that would replace the first occurrence of replacement starting from offset, or maybe you'd recommend some other way of solving this? Thanks!

我需要替换字符串中的一个单词,看起来像“duh duh something else duh”。我只需要替换第二个“duh”,但第一个和最后一个需要保持不变,因此 replace() 和 replaceFirst() 不起作用。是否有像 replaceFirst(String regex, String replacement, int offset) 这样的方法可以替换从偏移量开始的第一次替换,或者您可能会推荐一些其他方法来解决这个问题?谢谢!

回答by Chinmay Kanchi

What about something like this:

像这样的事情怎么样:

String replaceFirstFrom(String str, int from, String regex, String replacement)
{
    String prefix = str.substring(0, from);
    String rest = str.substring(from);
    rest = rest.replaceFirst(regex, replacement);
    return prefix+rest;
}

// or
s.substring(0,start) +  s.substring(start).replaceFirst(search, replace);

just 1 line of code ... not a whole method.

只有 1 行代码......不是一个完整的方法。

回答by polygenelubricants

Will something like this work?

这样的事情会起作用吗?

  System.out.println(
     "1 duh 2 duh duh 3 duh"
     .replaceFirst("(duh.*?)duh", "bleh")
  ); // prints "1 duh 2 bleh duh 3 duh"

If you just want to replace the second occurrence of a pattern in a string, you really don't need this "starting from" index calculation.

如果您只想替换字符串中第二次出现的模式,您真的不需要这种“从”索引计算。

As a bonus, if you want to replace every other duh(i.e. second, fourth, sixth, etc), then just invoke replaceAllinstead of replaceFirst.

作为奖励,如果您想每隔一个替换duh(即第二个、第四个、第六个等),那么只需调用replaceAll而不是replaceFirst.

回答by Michael Brewer-Davis

An alternative using Matcher:

使用Matcher的替代方法:

 String input = "duh duh something else duh";
 Pattern p = Pattern.compile("duh");
 Matcher m = p.matcher(input);
 int startIndex = 4;

 String output;

 if (m.find(startIndex)) {
     StringBuffer sb = new StringBuffer();
     m.appendReplacement(sb, "dog");
     m.appendTail(sb);
     output = sb.toString();
 } else {
     output = input;
 }