Prashant Gaur
Prashant Gaur

Reputation: 9828

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.

Upvotes: 3

Views: 6237

Answers (2)

Yu Hao
Yu Hao

Reputation: 122383

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.

Upvotes: 3

zx81
zx81

Reputation: 41838

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

Upvotes: 1

Related Questions