Using regexp in template to extract multiple strings and assign to variables

I currently have the following code in a Define Variables block within an automation:

variables:
  dates_string: >
    {{ trigger.event.data["text"] | regex_findall_index("[0-9]{1,2} [a-zA-Z]{3}
    [0-9]{4} - [0-9]{1,2} [a-zA-Z]{3} [0-9]{4}") }}
  booking_dates:
    start: "{{ dates_string.split(' - ')[0] }}"
    end: "{{ dates_string.split(' - ')[1] }}"

That successfully extracts two dates from an email e.g. “22 May 2026 - 26 May 2026” and now I’d like to extend it to also extract a word that follows those two dates. I’m happy with the regexp and understand that I need to use regex_findall and groups but don’t know how to assign the found matches to variables.

I believe the regex_findall call will be as follows:

regex_findall("([0-9]{1,2} [a-zA-Z]{3} [0-9]{4}) - ([0-9]{1,2} [a-zA-Z]{3} [0-9]{4}) \t([a-zA-Z]+) \t")

An example of the string is:
“22 May 2026 - 26 May 2026 School”

If the text in the email is going to be simple like that, you really don’t need to do another full regex, you can just split by the end string and index select:

variables:
  dates_string: >
    {{ trigger.event.data["text"] | regex_findall_index("[0-9]{1,2} [a-zA-Z]{3} [0-9]{4} - [0-9]{1,2} [a-zA-Z]{3} [0-9]{4}") }}
  booking_dates:
    start: "{{ dates_string.split(' - ')[0] }}"
    end: "{{ dates_string.split(' - ')[1] }}"
  booking_word: |
    {% set text =  trigger.event.data["text"] %}
    {{ text.split(booking_dates.end)[1] }}

But, if there’s going to be a lot of text following the date and you specifically only want the first word, then you would use your second regex call:

variables:
  strings: >
    {{ trigger.event.data["text"]|regex_findall("([0-9]{1,2} [a-zA-Z]{3} [0-9]{4}) - ([0-9]{1,2} [a-zA-Z]{3} [0-9]{4}) ([a-zA-Z]+)")|first }}
  booking_dates:
    start: "{{ strings[0] }}"
    end: "{{ strings[1] }}"
  booking_word: "{{ strings[2]}}"

Copy-paste this into the Template Editor and experiment with it.

{% set text = 'bla bla bla 22 May 2026 - 26 May 2026 School bla bla bla' %}

{% set x = text | regex_findall("(\d+ \w+ \d+) - (\d+ \w+ \d+) (\w+)") | flatten %}

{{ x[0] }}
{{ x[1] }}
{{ x[2] }}

If it meets your requirements, you can use it like this:

variables:
  x: >
    {{ trigger.event.data["text"]
      | regex_findall("(\d+ \w+ \d+) - (\d+ \w+ \d+) (\w+)")
      | flatten }}
  booking_dates:
    start: "{{ x[0] }}"
    end: "{{ x[1] }}"
  location: "{{ x[2] }}"

Reference

regex_findall

Note

I recommend you do something like this to mitigate the possibility that regex_findall does not find a match and returns nothing.

  booking_dates:
    start: "{{ x[0] | default('') }}"
    end: "{{ x[1] | default('') }}"
  location: "{{ x[2] | default('') }}"
1 Like