Match#
relationalai.std.re
#class Match(Producer)
Represents a match returned by a regular expression operation, such as match()
, search()
or fullmatch()
.
Provides attributes and methods for getting details about the match.
Must be used in a rule or query context.
Attributes#
Name | Description | Type |
---|---|---|
.pos | The value of pos passed to match() , search() , or fullmatch() . This represents the starting position of the match or search. | Producer or Python int |
.re | The compiled regular expression object whose .match() , .search() , or .fullmatch() method returned this Match object. | Pattern |
.string | The string passed to match() , search() , or fullmatch() . | Producer or Python str |
Methods#
Name | Description | Return Type |
---|---|---|
.group() | Returns a subgroup of the match. | Expression |
.__getitem__() | Identical to .group() . Allows subscript access to individual groups from a match. | Expression |
.start() | Returns the starting position of the match. | Expression |
.end() | Returns the ending position of the match. | Expression |
.span() | Returns a tuple containing the starting and ending positions of the match. | tuple[Expression] |
Example#
Use the match()
, search()
, or fullmatch()
functions to get a Match
object:
#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="Barbara Liskov")
# =======
# EXAMPLE
# =======
# Set first_name and last_name properties for each person.
with model.rule():
person = Person()
match = re.match(r"(\w+) (\w+)", person.full_name)
person.set(first_name=match.group(1), last_name=match.group(2))
with model.query() as select:
person = Person()
response = select(person.id, person.first_name, person.last_name)
print(response.results)
# id first_name last_name
# 0 1 Alan Turing
# 1 2 Barbara Liskov
Match
objects can be assigned to object properties.
The property is assigned the full match string, and not the Match
object itself:
#with model.rule():
person = Person()
# Match full names starting with "B".
match = re.match(r"B.*", person.full_name)
# Set the matched_string property. This does not assign the Match object
# itself to the property, but rather the full match string.
person.set(matched_string=match)
with model.query() as select:
person = Person()
response = select(person.id, person.matched_string)
print(response.results)
# id matched_string
# 0 1 NaN
# 1 2 Barbara Liskov
# Since the Match object is not assigned to the property, you can't use its
# attributes or methods when accessing the matched_string property.
with model.query() as select:
person = Person()
match_start = person.matched_string.start() # Raises error
response = select(person.id, match_start)