1

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

6
  • Hi, welcome to StackOverflow. What have you tried so far? Commented Oct 24, 2018 at 18:16
  • Provide the code of what you have tried so far. Commented Oct 24, 2018 at 18:19
  • I tried using /v1/resource1 and /v1/resource/+ as couple of patterns but the second pattern matches both 2nd and 3rd URIs Commented Oct 24, 2018 at 18:22
  • Please share the code to repro the issue. Try the solution here - ideone.com/7sTHGs Commented Oct 24, 2018 at 18:47
  • @WiktorStribiżew, the solution worked correctly. Thanks a lot for the help Commented Oct 24, 2018 at 19:09

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.