Skip to content

Commit a275998

Browse files
committed
Use re.sub for ireplace - works better then my early attempts
1 parent 593ff63 commit a275998

2 files changed

Lines changed: 9 additions & 18 deletions

File tree

cloudbot/util/formatting.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -173,24 +173,12 @@ def ireplace(text, old, new, count=None):
173173
old replaced by new. If the optional argument count is given, only the first count
174174
occurrences are replaced.
175175
"""
176-
last_idx = 0
177-
idx = 0
178-
num = 0
179-
while idx < len(text):
180-
index_l = text.lower().find(old.lower(), idx)
181-
if index_l == -1:
182-
return text
183-
184-
text = text[:index_l] + new + text[index_l + len(old):]
185-
idx = index_l + len(old)
186-
num += 1
187-
if count and num >= count:
188-
break
189-
# if the function is just looping, end it
190-
if idx == last_idx:
191-
break
192-
last_idx = int(idx)
193-
return text
176+
pattern = re.compile(re.escape(old), re.IGNORECASE)
177+
178+
if count:
179+
return pattern.sub(new, text, count=count)
180+
else:
181+
return pattern.sub(new, text)
194182

195183

196184
def multi_replace(text, word_dic):

cloudbot/util/test/test_formatting.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ def test_ireplace():
9898
assert ireplace(test_ireplace_input, "fox", "cat", 1) == "The quick brown cat fox FOX jumped over the lazy dog"
9999
assert ireplace(test_ireplace_input, "fox", "cat", 2) == "The quick brown cat cat FOX jumped over the lazy dog"
100100

101+
# test blank input - this should behave like the native string.replace()
102+
assert ireplace("Hello", "", "?") == "?H?e?l?l?o?"
103+
101104

102105
def test_chunk_str():
103106
assert chunk_str(test_chunk_str_input, 10) == test_chunk_str_result

0 commit comments

Comments
 (0)