我有一个URL字符串,需要从匹配中获取某些单词. 例: /school/student/studentname1/detail/55/address/address1 我能够传递获取所需的细节,如, local s1,s2,s3 =myString:match("/school/student/(.-)/detail/(.-)/address
例:
/school/student/studentname1/detail/55/address/address1
我能够传递获取所需的细节,如,
local s1,s2,s3 =myString:match("/school/student/(.-)/detail/(.-)/address/(.-)")
现在的问题是我的字符串可以
myString = /school/student/studentname1
要么
myString = /school/student/studentname1/detail/55
在那种情况下,我的正则表达式失败,任何帮助?
local all_fields = { student = 1, detail = 2, address = 3 } local function parse(str) local info = {} local index for w in str:gmatch"/([^/]+)" do if index then info[index] = w index = nil else index = all_fields[w] end end return (table.unpack or unpack)(info, 1, 3) end local myString = '/school/student/studentname1/detail/55/address/address1' local s1, s2, s3 = parse(myString) print(s1, s2, s3) myString = '/school/student/studentname1/address/address1' s1, s2, s3 = parse(myString) print(s1, s2, s3) myString = '/school/student/studentname1/detail/55' s1, s2, s3 = parse(myString) print(s1, s2, s3)