Pattern.search()#

relationalai.std.re
#Pattern.search(string: str|Producer, pos: int|Producer = 0) -> Match

Searches a string for a match to the compiled pattern starting from position pos and returns a Match object for the first match found. If string or pos is a Producer, then .search() filters out non-string values from string and non-integer and negative values from pos. Must be used in a rule or query context.

Parameters#

NameTypeDescription
stringProducer or Python strThe string to search.
posProducer or Python intThe starting position of the search. Must be non-negative. (Default: 0)

Returns#

A Match object.

Example#

Use .search() to search for a substring that matches the compiled regular expression anywhere in a string, starting from a specified position:

#import relationalai as rai
from relationalai.std import re


# =====
# SETUP
# =====

model = rai.Model("MyModel")
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
# =======

# Compile a pattern for times in the format "HH:MM AM/PM"
pattern = re.compile(r"\d{1,2}:\d{2} [AP]M")

with model.rule():
    message = Message()
    # Search for the time pattern within each message starting at position 0.
    match = pattern.search(message.text)
    # Since search() filters out non-matching and non-string values, the
    # following properties are not set for messages with IDs 2 and 3.
    message.set(
        match_text=match,
        match_start=match.start(),
        match_end=match.end()
    )

with model.query() as select:
    message = Message()
    response = select(
        message.id,
        message.text,
        message.match_text,
        message.match_start,
        message.match_end,
    )

print(response.results)
#    id                          text match_text  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

See Also#