Pattern.match()#

relationalai.std.re
#Pattern.match(string: str|Producer, pos: int|Producer = 0) -> Match

Matches a string that begins with a compiled pattern starting from position pos and returns a Match object. If string or pos is a Producer, then .match() filters out non-string values from string and non-integer and negative values from pos. Must be used in a rule or query context.

Parameters#

NameTypeDescription
stringProducer or Python strThe string to match against.
posProducer or Python intThe starting position of the match. Must be non-negative. (Default: 0)

Returns#

A Match object.

Example#

Use .match() to match a compiled pattern at the beginning of a string, starting from a specified position:

#import relationalai as rai
from relationalai.std import re


# =====
# SETUP
# =====

model = rai.Model("MyModel")
Person = model.Type("Person")

with model.rule():
    Person.add(id=1).set(name="Alan Turing")
    Person.add(id=2).set(name="Bob")
    Person.add(id=3).set(name=-1)  # Non-string name


# =======
# EXAMPLE
# =======

# Compile a pattern for matching full names with groups for first and last names.
pattern = re.compile(r"(\w+) (\w+)")

with model.rule():
    person = Person()
    # Match the pattern within each person's name.
    match = pattern.match(person.name)
    # Use match.group() to set first_name and last_name properties. Since match()
    # filters out non-matching strings and non-string values, the following does
    # not set properties for Person objects with IDs 2 and 3.
    person.set(first_name=match.group(1), last_name=match.group(2))

with model.query() as select:
    person = Person()
    response = select(
        person.id,
        person.name,
        person.first_name,
        person.last_name
    )

print(response.results)
#    id         name first_name last_name
# 0   1  Alan Turing       Alan    Turing
# 1   2          Bob        NaN       NaN
# 2   3           -1        NaN       NaN

See Also#