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.

Parameters:
  • patterns_dir_or_dict (TemplateSource)

  • whitespace_noise (str | None)

  • flags (int)

patterns_src

The merged placeholder namespace from every template source.

Type:

dict[str, Any]

patterns_all

The runnable patterns per template name ($PATTERNS entries).

Type:

dict[str, list[str]]

patterns

The compiled patterns, as CompiledPattern objects.

Type:

list[replus.builder.CompiledPattern]

whitespace_noise

The whitespace-replacement pattern, if any.

Type:

str | None

flags

The regex flags patterns were compiled with.

Type:

int

__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 *.json template 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) – regex flags 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.

  • exclude (list[str] | None) – Skip patterns of these types.

  • 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 Match per raw regex match.

Return type:

Iterator[Match]

Note

Regex flags are a compile-time setting: pass them once to Replus (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 overlapped is 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.

  • exclude (list[str] | None) – Skip patterns of these types.

  • 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 Match objects, sorted by start offset.

Return type:

list[Match]

Note

Regex flags are a compile-time setting; see finditer().

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. a timeout on catastrophic backtracking later in the string) may not surface here as it would in parse().

Parameters:
  • string (str) – The string to match against.

  • filters (list[str] | None) – Only run patterns of these types (template names); all if None.

  • exclude (list[str] | None) – Skip patterns of these types.

  • 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 Match by position, or None.

Return type:

Match | None

Note

Regex flags are a compile-time setting; see finditer().

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 Group and 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(), except overlapped, which is not supported.

Returns:

The string with all replacements applied.

Raises:
Return type:

str

static purge_overlaps(matches)

Drop overlapping matches, keeping the longest one of each overlapping run.

Parameters:

matches (list[_M]) – Match or Group objects; sorted in place by start offset.

Returns:

The overlap-free list, sorted by start offset.

Return type:

list[_M]

Results

class replus.Match(compiled, match)

A single hit of a runnable pattern.

Parameters:
type

The match type — the stem of the template file the pattern came from.

compiled

The CompiledPattern that produced this match.

match

The underlying regex.Match.

partial

Whether this is a partial match.

value

The matched substring.

Type:

str

offset

{"start": int, "end": int} of the match.

Type:

dict[str, int]

pattern

The compiled pattern string.

length

Number of matched characters.

Type:

int

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.

Parameters:
  • group_query (str | None) – Only return groups of this key (e.g. every day_N).

  • root (bool) – If True, drop groups contained in other returned groups.

Return type:

list[Group]

end(group_name=None, rep_index=None)

Return the end offset of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

int

first()

Return the first nested group, or None.

Return type:

Group | None

group(group_name)

Return the first nested group whose key is group_name, or None.

Parameters:

group_name (str)

Return type:

Group | None

json(*args, **kwargs)

Return serialize() as a JSON string; arguments go to json.dumps().

Parameters:
Return type:

str

last()

Return the last nested group, or None.

Return type:

Group | None

serialize()

Return a plain-dict representation of this object and its nested groups.

Return type:

dict[str, Any]

span(group_name=None, rep_index=None)

Return the (start, end) span of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

tuple[int, int]

start(group_name=None, rep_index=None)

Return the start offset of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

int

class replus.Group(match, group_name, root, rep_index=0)

A named group captured inside a Match.

Parameters:
  • match (regex.Match[str])

  • group_name (str)

  • root (Match)

  • rep_index (int)

root

The Match this group belongs to.

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).

value

The captured substring for this repetition.

Type:

str

rep_index

Which repetition of the group this object represents.

Type:

int

offset

{"start": int, "end": int} of the capture.

Type:

dict[str, int]

length

Number of captured characters.

Type:

int

groups(group_query=None, root=False)

Return the groups nested inside this one, sorted by start offset.

Parameters:
  • group_query (str | None) – Only return groups of this key (e.g. every day_N).

  • root (bool) – If True, drop groups contained in other returned groups.

Return type:

list[Group]

reps()

Return every repetition of this group as its own Group, or [] if single.

Return type:

list[Group]

end(group_name=None, rep_index=None)

Return the end offset of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

int

first()

Return the first nested group, or None.

Return type:

Group | None

group(group_name)

Return the first nested group whose key is group_name, or None.

Parameters:

group_name (str)

Return type:

Group | None

json(*args, **kwargs)

Return serialize() as a JSON string; arguments go to json.dumps().

Parameters:
Return type:

str

last()

Return the last nested group, or None.

Return type:

Group | None

serialize()

Return a plain-dict representation of this object and its nested groups.

Return type:

dict[str, Any]

span(group_name=None, rep_index=None)

Return the (start, end) span of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

tuple[int, int]

start(group_name=None, rep_index=None)

Return the start offset of self, or of the group named group_name.

Parameters:
  • group_name (str | None) – Name of a nested group to locate instead of self.

  • rep_index (int | None) – Repetition index; defaults to this object’s own.

Raises:

NoSuchGroupError – If group_name does not exist in this match.

Return type:

int

replus.purge_overlaps(matches)

Drop overlapping matches, keeping the longest one of each overlapping run.

Parameters:

matches (list[_M]) – Match or Group objects; sorted in place by start offset.

Returns:

The overlap-free list, sorted by start offset.

Return type:

list[_M]

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:
type

The match type — the stem of the template file (or dict key) it came from.

Type:

str

regex

The compiled regular expression.

Type:

_regex.Pattern[str]

template

The source template string, before expansion.

Type:

str

group_names

Generated group names, in order of creation (day_0, day_1, …).

Type:

tuple[str, …]

group_keys

Map of generated group name to its template key (day_1day).

Type:

dict[str, str]

order

Map of generated group name to its position in group_names.

Type:

dict[str, int]

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.