1
votes

I have below URIs:

  • /v1/resource1
  • /v1/resource1/{uuid}
  • /v1/resource1/{uuid}/resource2

I tried using /v1/resource1 and /v1/resource/+ as couple of patterns but the second pattern matches both 2nd and 3rd URIs

I want to have 3 separate patterns matching the above URIs separately. I am using string.match function for pattern matching.

Can someone help me with the Lua patterns?

Thanks

2
Hi, welcome to StackOverflow. What have you tried so far? - Saulo Silva
Provide the code of what you have tried so far. - SamHoque
I tried using /v1/resource1 and /v1/resource/+ as couple of patterns but the second pattern matches both 2nd and 3rd URIs - Hrishikesh P Nerurkar
Please share the code to repro the issue. Try the solution here - ideone.com/7sTHGs - Wiktor Stribiżew
@WiktorStribiżew, the solution worked correctly. Thanks a lot for the help - Hrishikesh P Nerurkar

2 Answers

1
votes

You may use

string.match("/v1/resource1", "^/v1/resource%d*$")
string.match("/v1/resource1/{uuid}", "^/v1/resource1/[^/]*$")
string.match("/v1/resource1/{uuid}/resource2", "^/v1/resource1/[^/]*/[^/]*$")

See the online Lua demo

Last pattern details

  • ^ - start of string
  • /v1/resource1/ - a literal string
  • [^/]* - 0 or more chars other than /
  • / - a / char
  • [^/]* - 0 or more chars other than /
  • $ - end of string.
0
votes

But I think, it would be better, to have an universal pattern that works for all strings, that have the same structure. So you should avoid literal strings inside pattern (except, you are looking for exactly this).

list_url = {'/v1/resource1','/v1/resource1/{uuid}','/v1/resource1/{uuid}/resource2'}

patt1 = '^/[^/]+/[^/]+'
patt2 = patt1..'/%{[^}]+}'
patt3 = patt2..'/[^/]+'

for _, url in pairs(list_url) do
    print(url)
    print('\t', url:match(patt1..'$'))
    print('\t', url:match(patt2..'$'))
    print('\t', url:match(patt3..'$'))
end

output:

/v1/resource1
    /v1/resource1
    nil
    nil
/v1/resource1/{uuid}
    nil
    /v1/resource1/{uuid}
    nil
/v1/resource1/{uuid}/resource2
    nil
    nil
    /v1/resource1/{uuid}/resource2