Reputation: 36249
Let's say I have the string /url/ID0123456789abcdef/bar
. I want to find and/or replace the ID0123456789abcdef
. This ID is always of the form of 2 alphabets, followed by 16 hex.
This is what I've done, and not sure if this is the best solution:
function replace_id(str, prefix, replace)
local first, last = str:find(prefix)
if first == nil then
return str
end
local hex = str:sub(last - 1, last + 16)
if not is_hex(hex) then
return str
end
return replace_id(str:gsub(hex, replace), prefix, replace)
end
function utils.is_hex(str)
if utils.is_str_empty(str) then
return false
end
-- String is alphanumeric and hex
return str:gsub('%a', ''):gsub('%d', '') == '' and str:gsub('%x', '') == ''
end
print(replace_id('/url/ID0123456789abcdef/bar', 'ID', 'REPLACED'))
-- Prints '/url/REPLACED/bar'
Is there a better way?
Upvotes: 2
Views: 785
Reputation: 7064
You're making things way harder than you need to.
A single call to string.gsub()
does what you want and all you need to do is build a pattern for what you want to match, which is quite easy.
The only thing to consider, if you wanted to build a pattern that contained magic characters like %
or .
you'd have to escape them first, which isn't that hard either, but that seems to not apply to your case anyway, as your prefix is only alphabetical characters.
function foo(str, prefix, replacement)
return str:gsub(prefix..string.rep("%x", 16), replacement)
end
This should do what you want just fine.
string.rep("%x", 16)
, as the name suggests, repeats the string 16 times, building a Lua pattern that matches 16 hexadecimal digits.
Upvotes: 4