Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(nodes): insert the String Replace replacement literally in plain-text mode (#10379)

Thejesh721ae3edb8ac
diff --git a/invokeai/app/invocations/strings.py b/invokeai/app/invocations/strings.py
index a294e7c667..6a1d8653f0 100644
--- a/invokeai/app/invocations/strings.py
+++ b/invokeai/app/invocations/strings.py
@@ -125,8 +125,10 @@ class StringReplaceInvocation(BaseInvocation):
pattern = self.search_string or ""
new_string = self.string or ""
if len(pattern) > 0:
- if not self.use_regex:
- # None regex so make case insensitve
- pattern = "(?i)" + re.escape(pattern)
- new_string = re.sub(pattern, (self.replace_string or ""), new_string)
+ replacement = self.replace_string or ""
+ if self.use_regex:
+ new_string = re.sub(pattern, replacement, new_string)
+ else:
+ # Plain text: case-insensitive match, and a callable so backslashes in the replacement stay literal.
+ new_string = re.sub("(?i)" + re.escape(pattern), lambda _match: replacement, new_string)
return StringOutput(value=new_string)
diff --git a/tests/app/invocations/test_strings.py b/tests/app/invocations/test_strings.py
index e7700bbfcf..5de5136dc4 100644
--- a/tests/app/invocations/test_strings.py
+++ b/tests/app/invocations/test_strings.py
@@ -2,7 +2,7 @@ from unittest.mock import MagicMock
import pytest
-from invokeai.app.invocations.strings import StringSplitInvocation
+from invokeai.app.invocations.strings import StringReplaceInvocation, StringSplitInvocation
def test_string_split_blank_delimiter_splits_on_first_whitespace() -> None:
@@ -32,3 +32,28 @@ def test_string_split_splits_on_first_occurrence_of_delimiter() -> None:
assert output.string_1 == "a"
assert output.string_2 == "b, c"
+
+
+ ("string", "search", "replace", "expected"),
+ [
+ ("path is DIR", "dir", r"C:\new\folder", r"path is C:\new\folder"),
+ ("cost: X", "x", r"\1 dollars", r"cost: \1 dollars"),
+ ("a+b", "+", "\\\\", "a\\\\b"),
+ ("Cat cat CAT", "cat", "dog", "dog dog dog"),
+ ],
+)
+def test_string_replace_plain_text_inserts_the_replacement_literally(
+ string: str, search: str, replace: str, expected: str
+) -> None:
+ output = StringReplaceInvocation(string=string, search_string=search, replace_string=replace).invoke(MagicMock())
+
+ assert output.value == expected
+
+
+def test_string_replace_regex_mode_still_expands_group_references() -> None:
+ output = StringReplaceInvocation(
+ string="a1b2", search_string=r"(\d)", replace_string=r"<\1>", use_regex=True
+ ).invoke(MagicMock())
+
+ assert output.value == "a<1>b<2>"