2

I have a rest URL as a string --> rest/dashboard/person/hari/categrory/savingaccount/type/withdraw

In this I have to get the value between person and category && value between categrory and type. Because those value will dynamically change

rest/dashboard/person/{{}}/categrory/{{}}/type/withdraw

I tried with string.gsub(mystring, "([%w]+%/)([%w%d]+)"). But it seems it is not the correct wast to do it

Please help

4
  • 1
    /(%w+)/category/(%w+)/, and use match instead of gsub Commented Aug 13, 2018 at 15:56
  • ok sure i will try with match. Thanks Egor Commented Aug 13, 2018 at 15:58
  • local t = string.match("rest/dashboard/person/hari/categrory/savingaccount/type/withdraw" ,"/(%w+)/category/(%w+)/") print(t) It is printing nil. Anything i am missing Commented Aug 13, 2018 at 16:05
  • You misspelled the word category Commented Aug 13, 2018 at 17:23

2 Answers 2

4

string.match with captures is the right tool for the job. Try this:

s="rest/dashboard/person/hari/category/savingaccount/type/withdraw" 
print(s:match("/person/(.-)/category/(.-)/type/"))
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @ihf marking it as accepted answer. Any idea on what is wrong with thiss="rest/dashboard/person/hari/category/savingaccount/type/withdraw" local s1,s2,s3 = (s:match("/person/(.-)/category/(.-)/type/")) print (s1) print (s2) print (s3)
@Hari, your s:match returns two values but the parentheses around it reduce them to one.
3

You can use a lazy dot .- as suggested or a negated character class [^/]+

s="rest/dashboard/person/hari/category/savingaccount/type/withdraw" 
print(s:match("person/([^/]+)/category/"))
print(s:match("category/([^/]+)/type/"))

Demo

1 Comment

Fantastic, this instance was extremely helpful for my use case. Thanks!

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.