Search code examples
stringlualua-patterns

check that string starts and ends with a specific pattern in Lua


I have a table which is having string values

data_table = {'(?P<smartcache>.+)$', 'css', '123454', '(?P<version>.+)$'}

I am trying to see if a string startswith '(?P<' and endswith ')$' . I want a string in output which will be like

output_table = '/smartcache/css/123454/version'

I am facing problem to fetch values which are passed with patterns like I want to fetch 'smartcache' from (?P<smartcache>.+)$.

My Try:

out_string_value = (string.match(uri_regex, '[^(?P<].+[)$]')

here I am getting output as smartcache>.+)$ but I want smartcache.


Solution

  • local uri_regex = '(?P<smartcache>.+)$'
    local out_string_value = uri_regex:match('^%(%?P<([^>]+)>.*%)%$$')
    print(out_string_value)
    

    The Lua pattern ^%(%?P<([^>]+)>.*%)%$$ is similar to the regex ^\(\?P<([^>]+)>.*\)\$$ except that Lua pattern uses % to escape magic characters.