Skip to content

relationalai.std.re.sub()

sub(
regex: str|Producer,
repl: string|Producer,
string: str|Producer
) -> Expression

Replace all occurrences of regex is string with repl. If regex, repl, or string is a Producer, then sub() filters out non-string values from regex and repl and non-matching strings from string. Must be used in a rule or query context.

NameTypeDescription
regexProducer or Python strA regular expression string.
replProducer or Python strThe string to replace the matches with.
stringProducer or Python strThe string to match against.

An Expression object.

Use the sub() function to replace all occurrences of a regular expression in a string:

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(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 a initials property that replaces the name with the first letter of each word.
with model.rule():
person = Person()
person.set(initials=re.sub(r"(\w)\w+", r"\1.", person.full_name))
with model.query() as select:
person = Person()
response = select(person.id, person.full_name, person.initials)
print(response.results)
# id name initials
# 0 1 Alan Turing A. T.
# 1 2 Gottfried Wilhelm Leibniz G. W. L.
# 2 3 -1 NaN