aeidon/finder.py

Source code for module aeidon.finder from file aeidon/finder.py.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# -*- coding: utf-8 -*-

# Copyright (C) 2005 Osmo Salomaa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

"""String and regular expression finder and replacer."""

import re

__all__ = ("Finder",)


class Finder:

    """
    String and regular expression finder and replacer.

    :ivar ignore_case: ``True`` to ignore case when finding matches
    :ivar match: Regular expression object for the latest match of pattern
    :ivar match_span: Tuple of start and end position for match
    :ivar pattern: String or regular expression object to find
    :ivar pos: Current offset from the beginning of the text
    :ivar replacement: Plain- or regular expression replacement string
    :ivar text: Target text to find matches of pattern in
    """

    def __init__(self):
        """Initialize a :class:`Finder` instance."""
        self.ignore_case = False
        self.match = None
        self.match_span = None
        self.pattern = None
        self.pos = None
        self.replacement = None
        self.text = None

    def next(self):
        """
        Find the next match of pattern.

        Raise :exc:`StopIteration` if no next match found.
        Return tuple of match start, end position.
        """
        if self.pos is None:
            # Start new search from beginning.
            self.pos = 0
        if isinstance(self.pattern, str):
            text = self.text
            pattern = self.pattern
            if self.ignore_case:
                text = text.lower()
                pattern = pattern.lower()
            try:
                index = text.index(pattern, self.pos)
            except ValueError:
                raise StopIteration
            self.match_span = (index, index + len(pattern))
        else: # Regular expression
            match = self.pattern.search(self.text, self.pos)
            if match is None:
                raise StopIteration
            # Avoid getting stuck with zero-length regular expressions.
            if match.span() == self.match_span == (self.pos, self.pos):
                if self.pos == len(self.text):
                    raise StopIteration
                self.pos += 1
                return self.next()
            self.match = match
            self.match_span = match.span()
        self.pos = self.match_span[1]
        return self.match_span

    def previous(self):
        """
        Find the previous match of pattern.

        Raise :exc:`StopIteration` if no previous match found.
        Return tuple of match start, end position.
        """
        if self.pos is None:
            # Start new search from end.
            self.pos = len(self.text)
        if isinstance(self.pattern, str):
            text = self.text
            pattern = self.pattern
            if self.ignore_case:
                text = text.lower()
                pattern = pattern.lower()
            try:
                index = text.rindex(pattern, 0, self.pos)
            except ValueError:
                raise StopIteration
            self.match_span = (index, index + len(pattern))
        else: # Regular expression
            iterator = self.pattern.finditer(self.text)
            match = None
            while True:
                try:
                    candidate = next(iterator)
                    if candidate.end() > self.pos:
                        raise StopIteration
                except StopIteration:
                    break
                match = candidate
            if match is None:
                raise StopIteration
            # Avoid getting stuck with zero-length regular expressions.
            if match.span() == self.match_span == (self.pos, self.pos):
                if self.pos == 0:
                    raise StopIteration
                self.pos -= 1
                return self.previous()
            self.match = match
            self.match_span = match.span()
        self.pos = self.match_span[0]
        return self.match_span

    def replace(self, next=True):
        """
        Replace the current match of pattern.

        `next` should be ``True`` to finish at end of match, ``False`` for
        beginning. Raise :exc:`re.error` if bad replacement.
        """
        a, z = self.match_span
        orig_length = len(self.text)
        replacement = self.replacement
        if not isinstance(self.pattern, str):
            replacement = self.match.expand(self.replacement)
        self.text = self.text[:a] + replacement + self.text[z:]
        shift = len(self.text) - orig_length
        self.pos = ((z + shift) if next else a)
        # Adapt match span to new text length to avoid
        # getting stuck with zero-length regular expressions.
        if next and (self.match_span[0] == self.match_span[1]):
            self.match_span = (self.pos, self.pos)

    def replace_all(self):
        """
        Replace all occurences of pattern.

        Raise :exc:`re.error` if bad replacement.
        Return the amount of substitutions made.
        """
        self.pos = 0
        self.match = None
        self.match_span = None
        count = 0
        while True:
            try:
                self.next()
            except StopIteration:
                self.pos = len(self.text)
                self.match_span = None
                break
            self.replace()
            count += 1
        return count

    def set_regex(self, pattern, flags=re.DOTALL|re.MULTILINE):
        """
        Set and use regular expression as pattern.

        The default value for `flags` is ``DOTALL`` and ``MULTILINE``.
        ``IGNORECASE`` is automatically added to flags if :attr:`ignore_case`
        is ``True``.

        Raise :exc:`re.error` if bad pattern.
        """
        if self.ignore_case:
            flags = flags | re.IGNORECASE
        self.pattern = re.compile(pattern, flags)

    def set_text(self, text):
        """Set the target text to search in and reset position."""
        self.text = text
        self.match = None
        self.match_span = None
        self.pos = None