group()#
relationalai.std.re.Match
#Match.group(index: int|str|Producer = 0) -> Expression
Returns a subgroup captured by a regular expression match.
If index
is an integer, it returns the subgroup at that index, where 0
is the entire match.
If index
is a string, it returns the subgroup with that name.
Must be used in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
index | int , str , or Producer | The index or name of the subgroup to return. Default is 0 , which returns the entire match. |
Returns#
An Expression
object.
Example#
Use .group()
to extract subgroups from a match by index:
#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
# =======
with model.query() as select:
person = Person()
# Extract the first and last names of each person.
match = re.match(r"(\w+) (\w+)", person.name)
response = select(
alias(match.group(0), "full_name"), # Get the entire match
alias(match.group(1), "first_name"), # Get the first subgroup
alias(match.group(2), "last_name"), # Get the second subgroup
)
print(response.results)
# full_name first_name last_name
# 0 Alan Turing Alan Turing
# 1 Barbara Liskov Barbara Liskov
Named groups can be accessed by name:
#with model.query() as select:
person = Person()
# Extract the first and last names of each person using named groups.
match = re.match(r"(?P<first>\w+) (?P<last>\w+)", person.name)
response = select(
alias(match.group(0), "full_name"),
alias(match.group("first"), "first_name"), # Get the subgroup named "first"
alias(match.group("last"), "last_name"), # Get the subgroup named "last"
)
print(response.results)
# full_name first_name last_name
# 0 Alan Turing Alan Turing
# 1 Barbara Liskov Barbara Liskov
Alternatively, you can access subgroups using subscript notation:
#match[1] # Equivalent to match.group(1)
match["first"] # Equivalent to match.group("first")