Find Replace Multi-Pairs Feedback Loop Problem

By Xah Lee. Date: . Last updated: .

Find Replace Multi-Pairs Feedback Problem

If find replace pairs is done one after one, then you may end up with a substring that's not in the original input string nor in any of the find replace pairs. For example.

Input string:

Replace Pairs:

Result:

Required Condition of Occurrence

2021-09-06 the non intentional replacement happens when a replace string is a superset or subset of subsequent find string.

Example

text is: sa

Real World Example

replace feedback problem 2023-01-11 n4vct
find-replace multi-pairs feedback problem 2023-01-11 n4vct

JavaScript Example

const xx = "abcd";

const xpairs = [
  ["a", "c"],
  ["c", "d"],
];

const xresult = xpairs.reduce((a, b) => (a.replaceAll(b[0], b[1])), xx);

console.log(xresult === "dbdd");
JavaScript replace feedback 2023-01-11 6mPrh
JavaScript replace feedback 2023-01-11 6mPrh

WolframLang Example

WolframLang's find-replace function does not have this feedback problem.

StringReplace[ "abcd", {"a" -> "c","c" -> "d"} ] === "cbdd"
WolframLang replace feedback 2023-01-11
WolframLang replace feedback 2023-01-11

State of AI. Multiple String Replacement Problem

Multiple String Replacement Problem 2025-08-11 3915b
Multiple String Replacement Problem 2025-08-11 3915b
Multiple String Replacement Problem 2025-08-11 2c97c
Multiple String Replacement Problem 2025-08-11 2c97c
Multiple String Replacement Problem 2025-08-11 2caf3
Multiple String Replacement Problem 2025-08-11 2caf3

Solutions

Solution 1, Use Single Regex Connected with Or, with a Dictionary for Pairs

  1. Convert all find strings into a regex, connected with “or”.
  2. Convert the find replace pairs into a hashtable for efficiency, for later use.
  3. Do find on the regex, for each found, find the matched string, and replace it with corresponding item.

Solution 2, 2-pass. first pass replace the find strings with unique ID.

  1. Generate a random unique string list, same items as the pairs.
  2. Loop thru each pair and do find replace.
  3. For each found, replace it by corresponding unique string.
  4. Do another find replace loop thru unique string list.
  5. For each found, replace it by corresponding replacement string.