sub()#
relationalai.std.re.Pattern
#sub(
repl: string|Producer,
string: str|Producer,
pos: int|Producer = 0
) -> Expression
Filters strings that match a regular expression and replaces the matches with a string.
Similar to the sub()
function, but also accepts an optional pos
parameter to specify the starting position of the search.
Must be used in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
regex | str or Producer | A regular expression string. |
repl | str or Producer | The string to replace the matches with. |
string | str or Producer | The string to match against. |
Returns#
An Expression
object.
Example#
#import relationalai as rai
from relationalai.std import alias, re
# =====
# SETUP
# =====
model = rai.Model("people")
Person = model.Type("Person")
with model.rule():
Person.add(name="Alan Turing")
Person.add(name="Gottfried Wilhelm Leibniz")
# =======
# EXAMPLE
# =======
pattern = re.compile(r"Wilhelm")
with model.query() as select:
person = Person()
new_name = pattern.sub("W.", person.name)
response = select(
person.name,
alias(new_name, "new_name")
)
print(response.results)
# name new_name
# 0 Gottfried Wilhelm Leibniz Gottfried W. Leibniz