BistrBuilder
- class bistring.BistrBuilder(original)
Bases:
object
Bidirectionally transformed string builer.
A BistrBuilder builds a transformed version of a source string iteratively. Each builder has an immutable original string, a current string, and the in-progress modified string, with alignments between each. For example:
original: |The| |quick,| |brown| |🦊| |jumps| |over| |the| |lazy| |🐶| | | | | | | | \ \ \ \ \ \ \ \ \ \ \ current: |The| |quick,| |brown| |fox| |jumps| |over| |the| |lazy| |dog| | | | / / / modified: |the| |quick| |brown| ...
The modified string is built in pieces by calling
replace()
to change n characters of the current string into new ones in the modified string. Convenience methods likeskip()
,insert()
, anddiscard()
are implemented on top of this basic primitive.>>> b = BistrBuilder('The quick, brown 🦊 jumps over the lazy 🐶') >>> b.skip(17) >>> b.peek(1) '🦊' >>> b.replace(1, 'fox') >>> b.skip(21) >>> b.peek(1) '🐶' >>> b.replace(1, 'dog') >>> b.is_complete True >>> b.rewind() >>> b.peek(3) 'The' >>> b.replace(3, 'the') >>> b.skip(1) >>> b.peek(6) 'quick,' >>> b.replace(6, 'quick') >>> b.skip_rest() >>> s = b.build() >>> s.modified 'the quick brown fox jumps over the lazy dog'
- property alignment: bistring._alignment.Alignment
The alignment built so far from self.current to self.modified.
- Return type
- property remaining: int
The number of characters of the current string left to process.
- Return type
- property is_complete: bool
Whether we’ve completely processed the string. In other words, whether the modified string aligns with the end of the current string.
- Return type
- append(bs)
Append a bistr. The original value of the bistr must match the current string being processed.
- Return type
- skip_match(regex)
Skip a substring matching a regex, copying it unchanged.
- discard_match(regex)
Discard a substring that matches a regex.
- replace_match(regex, repl)
Replace a substring that matches a regex.
- Parameters
regex (
Union
[str
,Pattern
[str
]]) – The (possibly compiled) regular expression to match.repl (
Union
[str
,Callable
[[Match
[str
]],str
]]) – The replacement to use. Can be a string, which is interpreted as inre.Match.expand()
, or a callable, which will receive each match and return the replacement string.
- Return type
- Returns
Whether a match was found.
- replace_next(regex, repl)
Replace the next occurence of a regex.
- replace_all(regex, repl)
Replace all occurences of a regex.
- build()
Build the bistr.
- Return type
- Returns
A bistr from the original string to the new modified string.
- Raises
ValueError
if the modified string is not completely built yet.
- rewind()
Reset this builder to apply another transformation.
- Raises
ValueError
if the modified string is not completely built yet.- Return type