Pattern.findall()#

relationalai.std.re
#Pattern.findall(string: str|Producer) -> tuple[Expression]

Finds all non-overlapping matches of a compiled pattern in a string starting. Returns a tuple (index, substring) of Expression objects representing the 1-based index of the match and the matched substring. If string is a Producer, then Pattern.findall() filters out non-string values from string. Must be used in a rule or query context.

Parameters#

NameTypeDescription
stringProducer or Python strThe string to search.
posProducer or Python intThe starting position of the search. (Default: 0)

Returns#

A tuple of two Expression objects.

Example#

Use .findall() to retrieve all non-overlapping matches of a compiled pattern in a string, along with their 1-based match index:

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


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

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

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


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

# Compile a pattern to find all words in a full name.
pattern = re.compile(r"(\w+)")

with model.rule():
    person = Person()
    index, word = pattern.findall(person.full_name)

    # Count the number of words per person.
    num_words = aggregates.count(index, per=[person])

    with model.match():
        # Set the first_name property to the first word.
        with index == 1:
            person.set(first_name=word)
        # Set the last_name property to the last word.
        with index == num_words:
            person.set(last_name=word)
        # Set the middle_name property if there are more than 2 words.
        with model.case():
            person.set(middle_name=word)


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

print(response.results)
#    id                  full_name first_name middle_name last_name
# 0   1                Alan Turing       Alan         NaN    Turing
# 1   2  Gottfried Wilhelm Leibniz  Gottfried     Wilhelm   Leibniz
# 2   3                         -1        NaN         NaN       NaN

In the preceding example, with statements handle conditional assignments based on the match index, setting first_name, middle_name, and last_name appropriately. See Expressing if-else Using model.match() for more details on conditional logic in RAI Python.

See Also#