Minor updates
This commit is contained in:
+26
-11
@@ -2,7 +2,7 @@ import re
|
||||
|
||||
class StringReplaceNode:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"replacement_pairs": ("STRING", {"multiline": True, "default": "",
|
||||
@@ -23,10 +23,14 @@ class StringReplaceNode:
|
||||
FUNCTION = "string_replace"
|
||||
CATEGORY = "utils"
|
||||
|
||||
def string_replace(self, input_string, replacement_pairs, replacement_delimiter, match_case, match_whole_string, remove_extra_spaces):
|
||||
result = input_string
|
||||
flags = 0 if match_case else re.IGNORECASE
|
||||
def cleanup_text(self, text):
|
||||
text = re.sub(r'\s+([,;:.])', r'\1', text) # Remove spaces before punctuation
|
||||
text = re.sub(r'\s{2,}', ' ', text) # Normalize multiple spaces
|
||||
return text.strip()
|
||||
|
||||
def string_replace(self, input_string, replacement_pairs, replacement_delimiter, match_case, match_whole_string, remove_extra_spaces):
|
||||
# Create a list of all replacements
|
||||
replacements = []
|
||||
for line in replacement_pairs.splitlines():
|
||||
line = line.strip()
|
||||
if not line or replacement_delimiter not in line:
|
||||
@@ -38,17 +42,28 @@ class StringReplaceNode:
|
||||
|
||||
if not search_str:
|
||||
continue
|
||||
|
||||
replacements.append((len(search_str), search_str, replace_str))
|
||||
|
||||
# Sort by length in descending order
|
||||
replacements.sort(reverse=True)
|
||||
|
||||
result = input_string
|
||||
flags = 0 if match_case else re.IGNORECASE
|
||||
|
||||
# Perform replacements
|
||||
for _, search_str, replace_str in replacements:
|
||||
if match_whole_string:
|
||||
pattern = re.escape(search_str)
|
||||
pattern = r"(?<!\S)" + pattern + r"(?!\S)"
|
||||
# Enhanced pattern to handle punctuation properly
|
||||
pattern = r'(?:\b|(?<=\s)|^)' + re.escape(search_str) + r'(?:[,;:.])?(?=\s|$)'
|
||||
else:
|
||||
pattern = re.escape(search_str)
|
||||
|
||||
result = re.sub(pattern, replace_str, result, flags=flags)
|
||||
# For non-whole string matching, still handle punctuation
|
||||
pattern = re.escape(search_str) + r'(?:[,;:.])?'
|
||||
|
||||
regex = re.compile(pattern, flags=flags)
|
||||
result = regex.sub(replace_str, result)
|
||||
|
||||
if remove_extra_spaces:
|
||||
result = re.sub(r'\s+', ' ', result)
|
||||
result = result.strip()
|
||||
result = self.cleanup_text(result)
|
||||
|
||||
return (result,)
|
||||
Reference in New Issue
Block a user