Skip to content

relationalai.std.re.search()

search(regex: str|Producer, string: str|Producer) -> Match

Scans a string for a regular expression match and returns a Match object for the first match found. If regex or string is a Producer, then search() filters out non-string regex values and non-matching string values from the producers. Must be used in a rule or query context.

NameTypeDescription
regexProducer or Python strA regular expression string.
stringProducer or Python strThe string to search.

A Match object.

Use the search() function to search for a substring that matches a regular expression anywhere in a string:

#
import relationalai as rai
from relationalai.std import alias, re
# =====
# SETUP
# =====
model = rai.Model("MyModel4")
Message = model.Type("Message")
with model.rule():
Message.add(id=1).set(text="The party starts at 8:00 PM.")
Message.add(id=2).set(text="Bring tacos")
Message.add(id=3).set(text=-1) # Non-string text
# =======
# EXAMPLE
# =======
with model.rule():
message = Message()
# Filter messages that contain a time in the format "HH:MM AM/PM".
match = re.search(r"\d{1,2}:\d{2} [AP]M", message.text)
# Since search() filters out non-matching strings and non-string values,
# the following does not set properties for the messages with IDs 2 and 3.
message.set(match=match, match_start=match.start(), match_end=match.end())
with model.query() as select:
message = Message()
response = select(
message.id,
message.text,
message.match,
message.match_start,
message.match_end,
)
print(response.results)
# id text match match_start match_end
# 0 1 The party starts at 8:00 PM. 8:00 PM 20.0 27.0
# 1 2 Bring tacos NaN NaN NaN
# 2 3 -1 NaN NaN NaN