It is also possible to do this without a more complex regular expression if you are looking for a more iterative solution, if you are so prone. You can divide by " and replace even-numbered indexes, and then rearrange the row.
String input = "\"unique\" unique unique \"unique\" \"unique\" \"unique\" \"unique\" unique \"unique unique\" unique unique \""; System.out.println(input); String[] split = input.split("\""); for (int i = 0; i < split.length; i = i + 2) { split[i] = split[i].replaceAll("unique", "potato"); } String output = ""; for (String s : split) { output += s + "\""; } System.out.println(output);
Output:
"unique" unique unique "unique" "unique" "unique" "unique" unique "unique unique" unique unique " "unique" potato potato "unique" "unique" "unique" "unique" potato "unique unique" potato potato "
source share