Cedric
Cedric

Reputation: 107

Find word in a string using a regex pattern lua

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

Upvotes: 2

Views: 1361

Answers (2)

lhf
lhf

Reputation: 72312

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/"))

Upvotes: 4

wp78de
wp78de

Reputation: 18950

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

Upvotes: 3

Related Questions