diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 4e9f9c432e0..3580af3e2bd 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1397,10 +1397,15 @@ def regex_search(value, find="", ignorecase=False): def regex_findall_index(value, find="", index=0, ignorecase=False): """Find all matches using regex and then pick specific match index.""" + return regex_findall(value, find, ignorecase)[index] + + +def regex_findall(value, find="", ignorecase=False): + """Find all matches using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 - return re.findall(find, value, flags)[index] + return re.findall(find, value, flags) def bitwise_and(first_value, second_value): @@ -1565,6 +1570,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["regex_match"] = regex_match self.filters["regex_replace"] = regex_replace self.filters["regex_search"] = regex_search + self.filters["regex_findall"] = regex_findall self.filters["regex_findall_index"] = regex_findall_index self.filters["bitwise_and"] = bitwise_and self.filters["bitwise_or"] = bitwise_or diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index d10ef114992..efdcebf70e1 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1110,6 +1110,17 @@ def test_regex_replace(hass): assert tpl.async_render() == ["Home Assistant test"] +def test_regex_findall(hass): + """Test regex_findall method.""" + tpl = template.Template( + """ +{{ 'Flight from JFK to LHR' | regex_findall('([A-Z]{3})') }} + """, + hass, + ) + assert tpl.async_render() == ["JFK", "LHR"] + + def test_regex_findall_index(hass): """Test regex_findall_index method.""" tpl = template.Template(