Sounds like at least one such entity's trigger attribute doesn't match the regex. In the spelled out loop, you'd still get the exception on a failed match, but you'd store the results for however many entities matched before then (so catching the exception and continuing on would work). List comprehensions are all or nothing; if an exception is raised before it finishes, the list in progress is thrown away.
While wasteful, this should work just fine:
named_entities = [name_regex.match(entity.trigger).group(1) for entity in entities[0] if name_regex.match(entity.trigger)]
or in 3.8 with assignment expression to avoid repetitive work:
named_entities = [match.group(1) for entity in entities[0] if match := name_regex.match(entity.trigger)]
The former is wasteful, but works in any Python version; the latter is directly equivalent to:
named_entities = []
for entity in entities[0]:
match = name_regex.match(entity.trigger)
if match:
named_entities.append(match.group(1))
The ultimate problem is your regex isn't always matching; list comprehensions just change whether or no you store the partial results. |