match()#

relationalai.std.re
#match(regex: str|Producer, string: str|Producer) -> Match

Filters strings that begin with a match for the specified regular expression and returns a Match object. If regex or string is a Producer, then match() filters out non-string regex values and non-matching string values from the producers. Must be used in a rule or query context.

TIP

When passing a string literal, use a raw string — which is prefaced with an r, as in r"J.*" — to avoid escaping special characters in regular expressions.

Parameters#

NameTypeDescription
regexProducer or Python strA regular expression string.
stringProducer or Python strThe string to match against.

Returns#

A Match object.

Example#

Use the match() function to match a regular expression at the beginning of a string:

#import relationalai as rai
from relationalai.std import alias, re


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

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

with model.rule():
    Person.add(id=1).set(name="Alice Johnson")
    Person.add(id=2).set(name="Bob")
    Person.add(id=3).set(name="Carol Smith")
    Person.add(id=4).set(name=-1)  # Non-string name


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

with model.rule():
    person = Person()
    # Match full names with groups for first and last names.
    match = re.match(r"(\w+) (\w+)", 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 4.
    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  Alice Johnson      Alice   Johnson
# 1   2            Bob        NaN       NaN
# 2   3    Carol Smith      Carol     Smith
# 3   4             -1        NaN       NaN

See Also#