Error: Failed to edit, could not find the string to replace (old_string problem)

Lately I keep getting this error and the AI can go into an infinite loop. It’s very frustrating:

“Error: Failed to edit, could not find the string to replace.”

Sometimes it gives an error like this:

“Error: Failed to edit, expected 1 occurrence but found 2.”

It usually says something about old_string not matching.