Pattern#
relationalai.std.re
#class Pattern
Represents a compiled regular expression object that can be used to match or search strings.
Use the compile()
function to create a Pattern
object.
Attributes#
Name | Type | Description |
---|---|---|
.pattern | str | The pattern string from which the Pattern object was compiled. |
Methods#
Name | Description | Returns |
---|---|---|
.match() | Filters strings that match the pattern. | Match |
.search() | Filters strings that contain a match. | Match |
.fullmatch() | Filters strings that match the pattern exactly. | Match |
.findall() | Filters strings that match the pattern and returns a tuple (index, string) of non-overlapping matches. | tuple[Expression] |
.sub() | Filters strings that match the pattern and replaces the matches with a string. | Expression |
Example#
Use the compile()
function to create a Pattern
object:
#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="Barbara Liskov")
# =======
# EXAMPLE
# =======
pattern = re.compile(r"(\w+) (\w+)")
with model.query() as select:
person = Person()
# Filter people whose name matches the pattern.
match = pattern.match(person.name)
# Get the first and last names of each person.
response = select(
person.name,
alias(match.group(1), "first_name"),
alias(match.group(2), "last_name"),
)
print(response.results)
# name first_name last_name
# 0 Alan Turing Alan Turing
# 1 Barbara Liskov Barbara Liskov