Pattern.sub()#

relationalai.std.re
#Pattern.sub(repl: str|Producer, string: str|Producer) -> Expression

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

Parameters#

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

Returns#

An Expression object.

Example#

Use .sub() to replace all occurrences of a compiled pattern 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
# =======

# Compile a pattern to replace middle names with initials.
pattern = re.compile(r"(\w)\w+")

with model.rule():
    person = Person()
    person.set(initials=pattern.sub(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                  full_name  initials
# 0   1                Alan Turing     A. T.
# 1   2  Gottfried Wilhelm Leibniz  G. W. L.
# 2   3                         -1       NaN

See Also#