Skip to content

relationalai.std.re.findall()

findall(regex: str|Producer, string: str|Producer) -> tuple[Expression]

Finds all non-overlapping matches of a regular expression in a string. Returns a tuple (index, substring) of Expression objects that produce the 1-based index of the match and the matched substring. If regex or string is a Producer, then findall() filters out non-string regex values and non-matching string values from the producers. Must be called in a rule or query context.

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

A tuple of two Expression objects.

Use the findall() function to find all non-overlapping matches of a regular expression in a string:

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
# =======
# Set first, last, and middle names for each person.
with model.rule():
person = Person()
# Find all words in the full name.
index, word = re.findall(r"(\w+)", 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.