To begin with, your original patter was not working as expected since it did not capture the address (because you used .-
which is not greedy)
So one way to fix the original patter could be using /school/student/([^/]+)/detail/([^/]+)/address/([^/]+)
where [^/]
means any character except /
Then, in order to optionally match some options and since lua patterns does not allow optional groups, you may need to use several steps like this:
myString = "/school/student/studentname1/detail/55"
local s1,s2,s3
s1 =myString:match("/school/student/([^/]+)")
if (s1 ~= nil) then
print(s1)
s2 =myString:match("/detail/([^/]+)")
if (s2 ~= nil) then
print(s2)
s3 =myString:match("/address/([^/]+)")
if (s3 ~= nil) then
print(s3)
end
end
end
Finally, if you want to make sure that detail and address appear exactly on that order, you may use this:
myString = "/school/student/studentname1/address/myaddress"
local s1,s2,s3
s1 =myString:match("/school/student/([^/]+)")
if (s1 ~= nil) then
print(s1)
s1,s2 =myString:match("/school/student/([^/]+)/detail/([^/]+)")
if (s2 ~= nil) then
print(s2)
s1,s2,s3 =myString:match("/school/student/([^/]+)/detail/([^/]+)/address/([^/]+)")
if (s3 ~= nil) then
print(s3)
end
end
end
That way it will find /school/student/studentname1/detail/55
but it will not find /school/student/studentname1/address/myaddress
. If you don't need it like this, just use the first version.