[text] add 'rextr()'

This commit is contained in:
Mike Fährmann
2025-05-23 17:28:58 +02:00
parent e8b7d93b43
commit f3ed15573a
3 changed files with 36 additions and 4 deletions

View File

@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright 2015-2022 Mike Fährmann
# Copyright 2015-2025 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
@@ -147,6 +147,15 @@ def rextract(txt, begin, end, pos=-1):
return None, pos
def rextr(txt, begin, end, pos=None, default=""):
"""Stripped-down version of 'rextract()'"""
try:
first = txt.rindex(begin, None, pos) + len(begin)
return txt[first:txt.index(end, first)]
except Exception:
return default
def extract_all(txt, rules, pos=0, values=None):
"""Calls extract for each rule and returns the result in a dict"""
if values is None:

View File

@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
# Copyright 2016-2023 Mike Fährmann
# Copyright 2016-2025 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
__version__ = "1.29.7"
__version__ = "1.30.0-dev"
__variant__ = None

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2015-2022 Mike Fährmann
# Copyright 2015-2025 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
@@ -241,6 +241,29 @@ class TestText(unittest.TestCase):
self.assertEqual(f(txt , value, ">") , (None, -1))
self.assertEqual(f(txt , "<" , value), (None, -1))
def test_rextr(self, f=text.rextr):
txt = "<a><b>"
self.assertEqual(f(txt, "<", ">"), "b")
self.assertEqual(f(txt, "X", ">"), "")
self.assertEqual(f(txt, "<", "X"), "")
# 'pos' argument
for i in range(10, 3, -1):
self.assertEqual(f(txt, "<", ">", i), "b")
for i in range(3, 0, -1):
self.assertEqual(f(txt, "<", ">", i), "a")
# 'default' argument
self.assertEqual(f(txt, "[", "]", -1, "none"), "none")
self.assertEqual(f(txt, "[", "]", None, "none"), "none")
self.assertEqual(f(txt, "[", "]", default="none"), "none")
# invalid arguments
for value in INVALID:
self.assertEqual(f(value, "<" , ">") , "")
self.assertEqual(f(txt , value, ">") , "")
self.assertEqual(f(txt , "<" , value), "")
def test_extract_all(self, f=text.extract_all):
txt = "[c][b][a]: xyz! [d][e"