Java String.replaceFirst (), which takes an argument from the beginning

I need to replace the word in a line similar to "duh duh something else duh". I only need to replace the second "duh", but the first and last should remain intact, so replace () and replaceFirst () do not work. Is there a method like replaceFirst (String regex, String replacement, int offset) that would replace the first substitution starting at the offset, or maybe you would recommend another way to solve this? Thanks!

+6
java string regex replace
source share
3 answers

Something like that:

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 the whole method.

+9
source share

Will there be something like this work?

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

If you just want to replace the second occurrence of the pattern in a string, you really don't need this β€œstarting with” index calculation.

As a bonus, if you want to replace all other duh (i.e. second, fourth, sixth, etc.), just call replaceAll instead of replaceFirst .

+4
source share

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; } 
+2
source share

All Articles