Atom: A Single Regex Element#

class my.regex.meta.Atom.Atom(data: str | Self = '', *args: Any)#

An immutable, atomic element of a regex expression (e.g. characters, sets, & groups).

Collections (sets and groups) can be broken down further in a way by identifying their alternating matches, but all atoms nonetheless share the quality of being indivisible in the context of the original expression that contains them.

Examples

Inspect an atom’s parts and shape:

>>> atom = Atom(r'\d{2,4}')
>>> atom.base, str(atom.quantifier)
('\\d', '{2,4}')
>>> Atom(r'(?:ab)+').is_group, Atom(r'[ab]').is_set
(True, True)

I Initial Methods#

classmethod Atom.plain_atomize(expr: str) → Generator[Self]#

Iteratively generate plain atoms from the given expression.

Important

This function is “plain” because it does NOT handle groups or sets – the caller must guarantee that neither type of atom appears in the snippet before calling this function.

For general-purpose atomization, see Regex.atomize().

Parameters:

expr – The regex expression snippet to atomize.

Yields:

Atom objects representing each atomic element in the expression.

Examples

Break a group-free snippet into its atoms:

>>> list(Atom.plain_atomize(r'ab\d+c?'))
['a', 'b', '\\d+', 'c?']

II Properties#

property Atom.quantifier: Quantifier#

The quantifier applied to this atom, empty if it has none.

property Atom.base: str#

The unqualified ‘base’ text of this atom, i.e. its data without any quantifier.

property Atom.is_optional: bool#

Whether this atom has an optional quantifier (e.g. ?, *, {0,3}).

property Atom.is_group: bool#

Whether this atom is a group (e.g. (?:abc)).

property Atom.is_set: bool#

Whether this atom is a character set (e.g. [A-Za-z]).

property Atom.is_simple: bool#

a single literal w/ no repeating quantifier.

Type:

Whether this atom is ‘simple’

III Methods#

Atom.quantify(quantifier: str | Quantifier, overwrite: bool = True) → Atom#

Create a copy of this atom with the given quantifier applied.

Parameters:
  • quantifier – The quantifier string to apply (e.g. ?, *+, {2,5}).

  • overwrite – Whether to overwrite any existing quantifier; if False, the two quantifiers are combined instead (wrapping in a new group when necessary).

Returns:

A new, quantified atom (the original object is NOT modified).

Examples

Apply a quantifier directly, or combine it with an existing one:

>>> Atom('a').quantify('{2,5}')
'a{2,5}'
>>> Atom('a+').quantify('?', overwrite=False)
'a*'
Atom.as_optional() → Atom#

Generate a copy of this atom with its quantifier made optional (e.g. a -> a?).

Atom.as_required() → Self#

Generate a copy of this atom with its quantifier made required (e.g. a* -> a+).