how I can do a replacement to an element in specific index without replace all the same elements in other index as a string in java

Viewed 54

how I can do a replacement to an element in specific index without replace all the same elements in other index as a string in java , like input a string "22" ,and you should make the last char be 0 , so if I did the built-in method , string.replace(oldchar,newchar) ,it'll replace the first 2 too , because I replaced a char to another , not index to another one ,so what the solution in java ?!

1 Answers

Use a regex negative lookahead:

str = str.replaceAll("2(?!.*2)", "0");

Regex breakdown:

  • 2 a literal "2"
  • (?!.*2) a negative lookahead for a "2", which in English means "a 2 does not exist after this point in the input"
Related