Page 1 of 1

wildcard in string

Posted: Saturday 26 October 2019 19:17
by pvklink
I have a the follwing equation
Can i make this line working for all doorsensors ?

if item.name == 'doorsensor_tuindeur_1' then -- kerui wifi devices kent open en dicht, generiek maken voor alle kerui's
<rest of the code>

something like:
if item.name == 'doorsensor*' then

Re: wildcard in string

Posted: Saturday 26 October 2019 20:43
by waaren
pvklink wrote: Saturday 26 October 2019 19:17 I have a the follwing equation. Can i make this line working for all doorsensors ?
if item.name == 'doorsensor_tuindeur_1' then -- kerui wifi devices kent open en dicht, generiek maken voor alle kerui's
<rest of the code>
Wildcards are handled a bit different in Lua then you might expect if you are used to other languages

You could use something like below function. It handles two types of wildcard chars
'*' wildcard for 0 or more chars.
'?' wildcard for 1 char

Code: Select all

local function matchesWildCardedString(stringToMatch, wildCardedString) 
    local magicalChars  =  '[^%w%s~{\\}:&(/)<>,?@#|_^*$]'  -- Lua 'magical chars' 
    local regExpression = ('^' .. wildCardedString:gsub("[%^$]",".")) -- make it a valid regexpression 
    
    if wildCardedString:find('*') and wildCardedString:find('?') then
        dz.log('Not possible to combine single char wildcard(s) "?" with multi char wildcard(s) "*"',dz.LOG_ERROR)
        return false
    elseif wildCardedString:find('*') then -- a * wild-card was used
        wildCardedString = (regExpression:gsub("*", ".*") .. '$'):gsub(magicalChars,'.') -- replace * with .* (Lua for zero or more of any char)
    elseif wildCardedString:find('?') then -- a ? wild-card was used
        wildCardedString = (regExpression:gsub("?", ".") .. '$'):gsub(magicalChars,'.') -- replace ? with . (Lua for single any char)
    end

    return stringToMatch:match(wildCardedString) == stringToMatch
end

if matchesWildCardedString(item.name, 'doorsensor*') then

Re: wildcard in string

Posted: Saturday 26 October 2019 21:18
by pvklink
wow, i thought this would be easy!
thanks!

Do i use it like this:
if matchesWildCardedString(item.name,'doorsensor*) then OR
if matchesWildCardedString(item.name,'doorsensor_tuindeur_?) then

Re: wildcard in string  [Solved]

Posted: Saturday 26 October 2019 21:55
by waaren
pvklink wrote: Saturday 26 October 2019 21:18 Do i use it like this:
if matchesWildCardedString(item.name,'doorsensor*) then OR
if matchesWildCardedString(item.name,'doorsensor_tuindeur_?) then
You can use either one (if you add the closing quotes) so

Code: Select all

if  matchesWildCardedString(item.name,'doorsensor*') then 
OR

Code: Select all

if  matchesWildCardedString(item.name,'doorsensor_tuindeur_?') then

Re: wildcard in string

Posted: Sunday 27 October 2019 8:24
by pvklink
Works great!
I placed it in global_data.lua