sub()#
relationalai.std.re
#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.
TIP
When passing a string literal, use a raw string — which is prefaced with an r
, as in r"J.*"
— to avoid escaping special characters in regular expressions.
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#
An Expression
object.
Example#
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