I’m very new to templates, so I’m hoping you can help.
I want to extract a portion of an MQTT topic name such as light_status_office/tele_ls/LWT or light_status_kitchen/tele_ls/LWT. I want to get the portion after light_status_ and before /tele_ls/LWT, for example, office or kitchen.
So far, I’m doing that as below, where topic3 = office. This works in dev_templates, but it seems kludgey.
{% set topic = "light_status_office/tele_ls/LWT" %}
{% set topic2 = topic.split("/")[0] %}
{% set topic3 = topic2.split("light_status_")[-1] %}
{{ topic3 }}
Is split the most appropriate filter to use for this? Can splits be nested, for example, so that there would be no need for topic3?
Overall, is there a better way to achieve the goal?
Thanks again. One thing I didn’t mention… Some of the room names I need to extract have an underscore in them, such as master_bedroom. (None have more than one underscore.)
So, while the first suggestion works, the second chops off the second word of the room name. Is there a way to control for that case?
This is a huge help in understanding how split works.
So this bit of funky text here: '(?<=_)([a-z]+)(?=\/)' means find all words (without numbers) between _ and /. Pair that with index=0, and you get the first one that it finds.
EDIT: If you change the index to index=1, it will find the second word between those characters. If that wasn’t clear. In your case, that would be the letters ls.