ADD: generalize regex_findall (#54584)

This commit is contained in:
Chris Browet 2021-09-05 12:41:39 +02:00 committed by GitHub
parent f8ebc31576
commit 5a2bcd2763
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -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

View File

@ -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(