Extracting a line from a list in an automation

I am trying to extract a line from a list (where I have done a match and replace) using REGEX and use the string as a variable. This is to set the media player to be the one I am asking from via HA voice PE albeit _2 for the music assistant entity. I have it working however it is by luck it works as what I have done tries the whole list of strings and fails until it finds the only string in the list that is valid .

The following is added to the trigger and the variable “voice_assistant_device” returns true instead of the string that it matches.

variables:
   voice_assistant: " {{ trigger.device_id }} 
   voice_assistant2_device: " {{ device_entities(voice_assistant) | regex_replace(find='media_player.home_assistant_voice_xxxxxx_media_player', replace='media_player.home_assistant_voice_xxxxxx_media_player_2', ignorecase=False) | regex_replace(find='media_player.home_assistant_voice_xxxxx3_media_player', replace='media_player.home_assistant_voice_xxxxx3_media_player_2', ignorecase=False)}} "
   voice_assistant_device: " {{ (voice_assistant2_device) | regex_match('^.*media_player.h.*', 0) }} "

You want regex_findall not regex_match.

1 Like

Thank you for your input

I now can play music via any HA voice PE device through one automation without duplication of actions etc (it targets the device I am talking/ requesting from).

I seem to have to add the lines below for each trigger_id unless there is a way to do this once for the entire automation?

Here is the working regex in the trigger.

variables:
  voice_assistant: " {{ trigger.device_id }} "
  voice_assistant_mediaplayer2: " {{ device_entities(voice_assistant) | regex_replace(find='_media_player', replace='_media_player_2', ignorecase=False) }} "
  voice_assistant_device: " {{ (voice_assistant_mediaplayer2) | regex_findall('media_player.h.*_2') }} "

You seem to be describing what are sometimes called “trigger-attached” variables. Those are generally meant for cases where each trigger needs it’s own distinct conditional logic. There are a number of places you can set up variables in an automation depending on how you need to use them. For your described use I would suggest creating a general variables block at the same level as triggers, conditions, and actions.

1 Like

Awesome! Much more efficient. Thank you @Didgeridrew