简体   繁体   中英

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 .

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.

I don't know the intricacies of Lua Pattern syntax, but in regex terms, this would be the pattern:

^\(\?P<([^>]+)>.*\)\$$

On the regex demo , you can see the match.

  • The ^ anchor asserts that we are at the beginning of the string
  • \\( matches an opening bracket
  • \\? matches a question mark
  • P< matches literal characters
  • ([^>]+) captures any chars that are not > to Group 1
  • > matches literal char
  • .* matches any chars
  • \\) matches a closing bracket
  • \\$ matches a dollar
  • The $ anchor asserts that we are at the end of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM