Regex to replace instances of `states.*.state` and `states.*.attributes.*`

Find and replace regex for state and attribute template lines

After the creation of a large amount of technical debt in which I kept using long and unpleasant syntax that can trigger errors on loading, I’ve created these two regex find and replace strings to clean up templates in my configuration and lovelace files. I figured folk might find them useful if they’ve found themselves in a similar situation to me.

State

The following regex can be used to find all instances of the discouraged states.sensor.example_sensor.state syntax and replace them with states('sensor.example_sensor') syntax instead.

Find


states\.((?:[a-z]|[A-Z]|_)+\.(?:[a-z]|[A-Z]|[0-9]|_)+)\.state

Replace


states('$1')

Attributes

The following regex can be used to find all instances of the discouraged states.sensor.example_sensor.attributes.example_attribute syntax and replace them with state_attr('sensor.example_sensor', 'example_attribute') syntax instead.

Find


states\.((?:[a-z]|[A-Z]|_)+\.(?:[a-z]|[A-Z]|[0-9]|_)+)\.attributes\.((?:[a-z]|[A-Z]|[0-9]|_)+)

Replace


state_attr('$1', '$2')

2 Likes