Find Replace Multi-Pairs Feedback Loop Problem
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:
abcd
Replace Pairs:
a
→c
cb
→x
Result:
- Expected:
cbcd
- Actual:
xcd
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.
- If superset, it always happen.
- If subset, it may happen.
Example
text is: sa
- subset situation:
- a → p
- sp → b
- superset situation:
- a → op
- p → b
Real World Example

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");

WolframLang Example
WolframLang's find-replace function does not have this feedback problem.
StringReplace[ "abcd", {"a" -> "c","c" -> "d"} ] === "cbdd"

State of AI. Multiple String Replacement Problem
- for coders. state of artificial intelligence.
- wow. extremely impressive.
- AI answered my question of vague description.
- Told me it's called Multiple String Replacement Problem.
- and indeed, checked out.


- brave search ai bot give further detail.
- it mentioned 2-pass solution, which is what i was doing.

Solutions
Solution 1, Use Single Regex Connected with Or, with a Dictionary for Pairs
- Convert all find strings into a regex, connected with “or”.
- Convert the find replace pairs into a hashtable for efficiency, for later use.
- 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.
- Generate a random unique string list, same items as the pairs.
- Loop thru each pair and do find replace.
- For each found, replace it by corresponding unique string.
- Do another find replace loop thru unique string list.
- For each found, replace it by corresponding replacement string.