What regular expression to use?

Given the payload:

var webdata_now_p = “1160”;

I got IndexError: list index out of range when testing in templating:

{{ value | regex_findall_index(‘var webdata_now_p = [0-9]+’)}}

Here is the sensor I’m trying to implement:

sensor:

  • platform: rest
    resource: http://192.168.1.81/status.html
    method: GET
    name: Actual Solar Power Production
    device_class: power
    value_template: “{{ value | regex_findall_index(‘var webdata_now_p = [0-9]+’) }}”
    verify_ssl: false
    unit_of_measurement: W
    authentication: basic
    username: the_username
    password: the_password
    force_update: true

Any help would be appreciated!

Please format your post correctly.

The regex search is picky about using double quotes. Try it as a multi line template with double quotes around your search expression (and no quotes outside the template).

Either one of these two simpler techniques will confirm the string contains 1160.

{{ value is search('1160') }}

{{ value[-6:-2] == '1160' }}

The first one searches for 1160 anywhere in the string whereas the second one searches for it in a specific place in the string.

Given that it is a power device class and the unit is W, I suspect 1160 was only an example and they want any number in that position.

2 Likes

Doh! :man_facepalming:


Try this:

{{ value | regex_findall_index('\d+') }}

If the value can contain a decimal point then use this:

{{ value | regex_findall_index('\d+.?\d+') }}

And if you get the same or a similar error, use the double quotes I mentioned:

value_template: >
  {{ value | regex_findall_index("\d+.?\d+") }}

Regex search seems really picky about this.

1 Like

One of the issues with regex_findall_index is that when it can’t find a match, it doesn’t fail gracefully. Note the error message in this example:

2 Likes

Ah! Good to know.

I concocted a way to avoid getting the error message in the case where regex_findall_index doesn’t find a match. Basically, it first tests if the value contains the desired pattern. If it does then it extracts it. If it doesn’t, it reports zero (or whatever one wants to use to represent ‘nothing found’).

{% set value = 'abc xyz' %}
{% set pattern = '\d+.?\d+' %}

{{ (value | regex_findall_index(pattern)) if value is search(pattern) else 0 }}

5 Likes

Thank you!

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. It helps users find answers to similar questions. For more information, refer to guideline 21 in the FAQ.