Skip to content

Commit 1d9fee7

Browse files
Add node for regex replace(sub) operation (#8340)
* Add node for regex replace(sub) operation * Apply suggestions from code review add tooltips Co-authored-by: Christian Byrne <abolkonsky.rem@gmail.com> * Fix indentation --------- Co-authored-by: Christian Byrne <abolkonsky.rem@gmail.com>
1 parent aeba0b3 commit 1d9fee7

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

comfy_extras/nodes_string.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,41 @@ def execute(self, string, regex_pattern, mode, case_insensitive, multiline, dota
296296

297297
return result,
298298

299+
300+
class RegexReplace():
301+
DESCRIPTION = "Find and replace text using regex patterns."
302+
@classmethod
303+
def INPUT_TYPES(s):
304+
return {
305+
"required": {
306+
"string": (IO.STRING, {"multiline": True}),
307+
"regex_pattern": (IO.STRING, {"multiline": True}),
308+
"replace": (IO.STRING, {"multiline": True}),
309+
},
310+
"optional": {
311+
"case_insensitive": (IO.BOOLEAN, {"default": True}),
312+
"multiline": (IO.BOOLEAN, {"default": False}),
313+
"dotall": (IO.BOOLEAN, {"default": False, "tooltip": "When enabled, the dot (.) character will match any character including newline characters. When disabled, dots won't match newlines."}),
314+
"count": (IO.INT, {"default": 0, "min": 0, "max": 100, "tooltip": "Maximum number of replacements to make. Set to 0 to replace all occurrences (default). Set to 1 to replace only the first match, 2 for the first two matches, etc."}),
315+
}
316+
}
317+
318+
RETURN_TYPES = (IO.STRING,)
319+
FUNCTION = "execute"
320+
CATEGORY = "utils/string"
321+
322+
def execute(self, string, regex_pattern, replace, case_insensitive=True, multiline=False, dotall=False, count=0, **kwargs):
323+
flags = 0
324+
325+
if case_insensitive:
326+
flags |= re.IGNORECASE
327+
if multiline:
328+
flags |= re.MULTILINE
329+
if dotall:
330+
flags |= re.DOTALL
331+
result = re.sub(regex_pattern, replace, string, count=count, flags=flags)
332+
return result,
333+
299334
NODE_CLASS_MAPPINGS = {
300335
"StringConcatenate": StringConcatenate,
301336
"StringSubstring": StringSubstring,
@@ -306,7 +341,8 @@ def execute(self, string, regex_pattern, mode, case_insensitive, multiline, dota
306341
"StringContains": StringContains,
307342
"StringCompare": StringCompare,
308343
"RegexMatch": RegexMatch,
309-
"RegexExtract": RegexExtract
344+
"RegexExtract": RegexExtract,
345+
"RegexReplace": RegexReplace,
310346
}
311347

312348
NODE_DISPLAY_NAME_MAPPINGS = {
@@ -319,5 +355,6 @@ def execute(self, string, regex_pattern, mode, case_insensitive, multiline, dota
319355
"StringContains": "Contains",
320356
"StringCompare": "Compare",
321357
"RegexMatch": "Regex Match",
322-
"RegexExtract": "Regex Extract"
358+
"RegexExtract": "Regex Extract",
359+
"RegexReplace": "Regex Replace",
323360
}

0 commit comments

Comments
 (0)