Regex expression in automation needs some tweaking

Hi there,

I have an automation that I’m working on. It involves needing a regex expression to be able to filter calendar events. The logic should be as follows:

  1. If event begins with the letter T, return false. End.
  2. If there are 3 or 4 consecutive digits, return True.

Some examples:
“T7575” = False (begins with T)
“ABC 867 ZXY” = True (867)
“Pickup” = False
“Some words (55:76)” = False (only 2 consecutive numbers)
“YGF AB658 YHJ” = True (658)
“YGF 6658 YHJ” = True (6658)

Basically, as long as the event doesn’t begin with T and there are 3 or 4 numbers in a row anywhere, it should be true.

Other notes:

  • Sometimes there will be letters next to the numbers, sometimes not
  • Will have to be able to work with spaces before/after the letters (and ignore them). Sometimes spaces will be there, sometimes not.

Here is what I have so far:

value_template: >-
      {{ trigger.calendar_event.summary |
      regex_match('^(?!T).*\\b\\d{3,4}\\b.*') }}

So far, entries such as “ABC 123 XYZ” have been returning true, as it should. However it appears to fail when there are letters immediately next to the numbers. For example: “ABC DE875 XZY” should return true, but it’s returning false right now.

Any help would be greatly appreciated! Thanks in advance.

You’re leading word boundary is killing it. Using your example:

ABC DE875 XZY

\d{3,4} matches 875, but because there’s an E before 8 then your word boundary isn’t matching.

Not knowing all your use-cases, I’m guessing you want something more like

^(?!T).*\\d{3,4}.*

So it’ll return true as long as there’s a string of 3 or 4 numbers. Not sure the word boundaries are even necessary

image

Handy regex tool:

1 Like

I ran this in regex 101 and it returns positive on your string.

^[A-S,U-Z,a-z,0-9].*\d{3,4}.*
1 Like

That did the trick! Thank-you very much for the correction and additional information. Much appreciated!

Thank-you very much as well! Good to have options as I learn yaml and regex. Appreciate your time.