API reference¶
Engine¶
- class replus.Replus(patterns_dir_or_dict, whitespace_noise=None, flags=regex.V0)¶
Builds and compiles regular expressions from templates, and matches them.
- patterns_all¶
The runnable patterns per template name (
$PATTERNSentries).
- patterns¶
The compiled patterns, as
CompiledPatternobjects.
- __init__(patterns_dir_or_dict, whitespace_noise=None, flags=regex.V0)¶
Instantiate the engine.
- Parameters:
patterns_dir_or_dict (TemplateSource) – Path to a directory of
*.jsontemplate files, or a dict mapping template names to template dicts.whitespace_noise (str | None) – If given, literal whitespace in patterns matches this pattern instead (e.g.
r"[\s\-]+").flags (int) –
regexflags to compile the patterns with.
- Return type:
None
- finditer(string, *, filters=None, exclude=None, pos=None, endpos=None, overlapped=False, partial=False, concurrent=None, timeout=None)¶
Lazily yield every match of every (selected) pattern, in pattern order.
Unlike
parse(), overlapping matches are not purged and results are not sorted by position.- Parameters:
string (str) – The string to match against.
filters (list[str] | None) – Only run patterns of these types (template names); all if None.
pos (int | None) – Start position of the matching.
endpos (int | None) – End position of the matching.
overlapped (bool) – Allow overlapping matches of the same pattern.
partial (bool) – Allow partial matches.
concurrent (bool | None) – Release the GIL while matching.
timeout (float | None) – Timeout in seconds for the matching.
- Yields:
One
Matchper raw regex match.- Return type:
Iterator[Match]
Note
Regex
flagsare a compile-time setting: pass them once toReplus(Replus(..., flags=regex.IGNORECASE)). They cannot be supplied per call, because the patterns are already compiled.
- parse(string, *, filters=None, exclude=None, pos=None, endpos=None, overlapped=False, partial=False, concurrent=None, timeout=None)¶
Return every match, sorted by position.
Unless
overlappedis True, overlapping matches are purged, keeping the longest match of each overlapping run.- Parameters:
string (str) – The string to match against.
filters (list[str] | None) – Only run patterns of these types (template names); all if None.
pos (int | None) – Start position of the matching.
endpos (int | None) – End position of the matching.
overlapped (bool) – Allow overlapping matches (and skip overlap purging).
partial (bool) – Allow partial matches.
concurrent (bool | None) – Release the GIL while matching.
timeout (float | None) – Timeout in seconds for the matching.
- Returns:
The list of
Matchobjects, sorted by start offset.- Return type:
Note
Regex
flagsare a compile-time setting; seefinditer().
- search(string, *, filters=None, exclude=None, pos=None, endpos=None, overlapped=False, partial=False, concurrent=None, timeout=None)¶
Return the first match of
parse(), or None.Returns the same match as
next(iter(parse(...)), None)but evaluated lazily: each pattern is scanned only as far as needed to settle the first (leftmost, overlap-purged) match, rather than materializing every match first. Because matching stops early, an error a pattern would raise only past that first match (e.g. atimeouton catastrophic backtracking later in the string) may not surface here as it would inparse().- Parameters:
string (str) – The string to match against.
filters (list[str] | None) – Only run patterns of these types (template names); all if None.
pos (int | None) – Start position of the matching.
endpos (int | None) – End position of the matching.
overlapped (bool) – Allow overlapping matches (and skip overlap purging).
partial (bool) – Allow partial matches.
concurrent (bool | None) – Release the GIL while matching.
timeout (float | None) – Timeout in seconds for the matching.
- Returns:
The first
Matchby position, or None.- Return type:
Match | None
Note
Regex
flagsare a compile-time setting; seefinditer().
- sub(string, replacements, **parse_kwargs)¶
Replace the captures of the given template keys inside every match.
Only matched spans are touched; the rest of the string passes through unchanged. Every repetition of a group is replaced. A string replacement is inserted literally (no escape processing); a callable receives the
Groupand returns the new text:engine.sub(text, {"prefix": lambda g: g.value.replace("1", "l")})
- Parameters:
string (str) – The string to match against.
replacements (Mapping[str, str | Callable[[Group], str]]) – Map of template key to replacement text, or to a callable computing it from the captured
Group.**parse_kwargs (Any) – Same keyword arguments as
parse(), exceptoverlapped, which is not supported.
- Returns:
The string with all replacements applied.
- Raises:
NoSuchGroupError – If a key is not defined by any compiled pattern.
OverlappingReplacementError – If two requested keys capture overlapping spans (e.g. a group and one of its children).
UnsupportedOperationError – If
overlapped=Trueis passed.
- Return type:
Results¶
- class replus.Match(compiled, match)¶
A single hit of a runnable pattern.
- Parameters:
compiled (CompiledPattern)
match (regex.Match[str])
- type¶
The match type — the stem of the template file the pattern came from.
- compiled¶
The
CompiledPatternthat produced this match.
- match¶
The underlying
regex.Match.
- partial¶
Whether this is a partial match.
- pattern¶
The compiled pattern string.
- all_group_names¶
Every group name the pattern can produce, in creation order.
- groups(group_query=None, root=False)¶
Return this match’s groups, sorted by start offset.
- end(group_name=None, rep_index=None)¶
Return the end offset of self, or of the group named
group_name.- Parameters:
- Raises:
NoSuchGroupError – If
group_namedoes not exist in this match.- Return type:
- group(group_name)¶
Return the first nested group whose key is
group_name, or None.
- json(*args, **kwargs)¶
Return
serialize()as a JSON string; arguments go tojson.dumps().
- serialize()¶
Return a plain-dict representation of this object and its nested groups.
- span(group_name=None, rep_index=None)¶
Return the
(start, end)span of self, or of the group namedgroup_name.
- start(group_name=None, rep_index=None)¶
Return the start offset of self, or of the group named
group_name.- Parameters:
- Raises:
NoSuchGroupError – If
group_namedoes not exist in this match.- Return type:
- class replus.Group(match, group_name, root, rep_index=0)¶
A named group captured inside a
Match.- match¶
The underlying
regex.Match.
- name¶
The generated group name, including its counter (e.g.
day_1).
- key¶
The template key of the group (e.g.
day).
- groups(group_query=None, root=False)¶
Return the groups nested inside this one, sorted by start offset.
- end(group_name=None, rep_index=None)¶
Return the end offset of self, or of the group named
group_name.- Parameters:
- Raises:
NoSuchGroupError – If
group_namedoes not exist in this match.- Return type:
- group(group_name)¶
Return the first nested group whose key is
group_name, or None.
- json(*args, **kwargs)¶
Return
serialize()as a JSON string; arguments go tojson.dumps().
- serialize()¶
Return a plain-dict representation of this object and its nested groups.
- span(group_name=None, rep_index=None)¶
Return the
(start, end)span of self, or of the group namedgroup_name.
- start(group_name=None, rep_index=None)¶
Return the start offset of self, or of the group named
group_name.- Parameters:
- Raises:
NoSuchGroupError – If
group_namedoes not exist in this match.- Return type:
Compiled patterns¶
- class replus.CompiledPattern(type, regex, template, group_names, group_keys, order)¶
A compiled runnable pattern plus the group metadata generated while building it.
- Parameters:
Exceptions¶
Exception hierarchy for replus.
Every error raised by replus inherits from ReplusError, so callers can
catch a single type to handle any library failure.
- exception replus.exceptions.ReplusError¶
Base class for all replus errors.
- exception replus.exceptions.DuplicatePatternKeyError¶
A template key is defined by more than one source file or dict.
- exception replus.exceptions.CircularReferenceError¶
Template keys reference each other in a cycle and can never be expanded.
- exception replus.exceptions.UnknownTemplateGroupError¶
A
{{placeholder}}references a key that is not defined in any template.
- exception replus.exceptions.InvalidBackreferenceError¶
A
{{#key}}backreference points to a group that has not been expanded yet.
- exception replus.exceptions.PatternBuildError¶
A fully expanded template failed to compile into a regular expression.
- exception replus.exceptions.NoSuchGroupError¶
A queried group name does not exist in the match.
- exception replus.exceptions.OverlappingReplacementError¶
Two replacement targets capture overlapping spans, so the edits are ambiguous.
- exception replus.exceptions.UnsupportedOperationError¶
An operation requested is not supported by the engine or method.