Skip to content
Advertisement

Detect if presence of a character in a string with Lua

I can have two types of string: nxs_flo_dev.nexus orfpdesk. I want to test if there is a . in the string. If there is a . I divide the string otherwise I do not do anything.

if(ngx.var.host.contains('.') then 
    content_by_lua 'ngx.say(ngx.var.host:match("(.-)%."))';
end

Is there a function to do that? Because .contains() doesn’t work.

Advertisement

Answer

Use match again. Remember to escape the dot with %.:

if ngx.var.host:match('%.') then 

If you want to do this inside content_by_lua do

content_by_lua 'if ngx.var.host:match('%.') then ngx.say(ngx.var.host:match("(.-)%.")) end';

Given your edit, this is the simplest solution:

content_by_lua 'ngx.say(ngx.var.host:match("(.-)%.") or ngx.var.host)';
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement