jenkins-bot has submitted this change and it was merged.
Change subject: Add count to replaceExcept ......................................................................
Add count to replaceExcept
Bug: T125307 Change-Id: I11eb1f341093e52951f701c8cb9b4a144742041c --- M pywikibot/textlib.py M tests/textlib_tests.py 2 files changed, 22 insertions(+), 3 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py index fc7c4b1..19aafa7 100644 --- a/pywikibot/textlib.py +++ b/pywikibot/textlib.py @@ -300,7 +300,7 @@
def replaceExcept(text, old, new, exceptions, caseInsensitive=False, - allowoverlap=False, marker='', site=None): + allowoverlap=False, marker='', site=None, count=0): """ Return text with 'old' replaced by 'new', ignoring specified types of text.
@@ -320,7 +320,9 @@ @type caseInsensitive: bool @param marker: a string that will be added to the last replacement; if nothing is changed, it is added at the end - + @param count: how many replacements to do at most. See parameter + count of re.sub(). + @type count: int """ # if we got a string, compile it as a regular expression if isinstance(old, basestring): @@ -336,8 +338,9 @@ dontTouchRegexes = _get_regexes(exceptions, site)
index = 0 + replaced = 0 markerpos = len(text) - while True: + while not count or replaced < count: if index > len(text): break match = old.search(text, index) @@ -412,6 +415,7 @@ # When the regex allows to match nothing, shift by one character index += 1 markerpos = match.start() + len(replacement) + replaced += 1 text = text[:markerpos] + marker + text[markerpos:] return text
diff --git a/tests/textlib_tests.py b/tests/textlib_tests.py index 103d848..6f6a288 100644 --- a/tests/textlib_tests.py +++ b/tests/textlib_tests.py @@ -1179,6 +1179,21 @@ ['invoke'], site=self.site), '{{#invoke:x}}')
+ def test_replace_with_count(self): + """Test replacing with count argument.""" + self.assertEqual(textlib.replaceExcept('x [[x]] x x', 'x', 'y', [], + site=self.site), + 'y [[y]] y y') + self.assertEqual(textlib.replaceExcept('x [[x]] x x', 'x', 'y', [], + site=self.site, count=5), + 'y [[y]] y y') + self.assertEqual(textlib.replaceExcept('x [[x]] x x', 'x', 'y', [], + site=self.site, count=2), + 'y [[y]] x x') + self.assertEqual(textlib.replaceExcept('x [[x]] x x', 'x', 'y', ['link'], + site=self.site, count=2), + 'y [[x]] y x') + def test_replace_tag_category(self): """Test replacing not inside category links.""" for ns_name in self.site.namespaces[14]:
pywikibot-commits@lists.wikimedia.org