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

前端 未结 3 1674
盖世英雄少女心
盖世英雄少女心 2020-12-19 05:10

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 unt

3条回答
  •  时光取名叫无心
    2020-12-19 05:48

    An alternative using 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;
     }
    

提交回复
热议问题