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#
Name | Type | Description |
---|---|---|
repl | Producer or Python str | The string to replace the matches with. |
string | Producer or Python str | The string to search for matches. |
pos | Producer or Python int | The 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