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.
Parameters
Section titled “Parameters”Name | Type | Description |
---|---|---|
regex | Producer or Python str | A regular expression string. |
repl | Producer or Python str | The string to replace the matches with. |
string | Producer or Python str | The string to match against. |
Returns
Section titled “Returns”An Expression
object.
Example
Section titled “Example”Use the sub()
function to replace all occurrences of a regular expression in a string:
import relationalai as raifrom 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