Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Util for Conversation."""
2 
3 from __future__ import annotations
4 
5 import re
6 
7 
8 def create_matcher(utterance: str) -> re.Pattern[str]:
9  """Create a regex that matches the utterance."""
10  # Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
11  # Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name}
12  parts = re.split(r"({\w+}|\[[\w\s]+\] *)", utterance)
13  # Pattern to extract name from GROUP part. Matches {name}
14  group_matcher = re.compile(r"{(\w+)}")
15  # Pattern to extract text from OPTIONAL part. Matches [the color]
16  optional_matcher = re.compile(r"\[([\w ]+)\] *")
17 
18  pattern = ["^"]
19  for part in parts:
20  group_match = group_matcher.match(part)
21  optional_match = optional_matcher.match(part)
22 
23  # Normal part
24  if group_match is None and optional_match is None:
25  pattern.append(part)
26  continue
27 
28  # Group part
29  if group_match is not None:
30  pattern.append(rf"(?P<{group_match.groups()[0]}>[\w ]+?)\s*")
31 
32  # Optional part
33  elif optional_match is not None:
34  pattern.append(rf"(?:{optional_match.groups()[0]} *)?")
35 
36  pattern.append("$")
37  return re.compile("".join(pattern), re.IGNORECASE)
re.Pattern[str] create_matcher(str utterance)
Definition: util.py:8