I wrote the following code:
rpid = "Remote-Party-ID:<sip:+19>;abc"
local startRPID = string.find(rpid, "<")
local endRPID = string.find(rpid, ">")
local ANI = string.sub(rpid, startRPID, endRPID)
local MRPID = "\"TEST\" "..ANI
local finalRPID = string.gsub(rpid,ANI,MRPID)
print (finalRPID)
Expected result:
Remote-Party-ID:"TEST" <sip:+19>;abc
However, the last replacement (string.gsub(rpid,ANI,MRPID)) is not happening because of the + character in ANI, so the actual result is Remote-Party-ID:<sip:+19>;abc.
If I pass the string without the + (rpid = "Remote-Party-ID:<sip:19>;abc"), the result is as expected (except for the +, which is of course also missing in the output).
How can I achieve the same with the + character included?
The proper way to do it
Your code goes around a couple corners to do a simple thing: You want to find the text enclosed in angle brackets (
<and>) and prepend something to it.This can be done using a single call to
string.gsub:This varies in some nuances:
1as a third parameter togsubto change this.but it handles your scenario correctly. Alternatively, you could also use
match; after all you don't need more than a single substitution:Fixing your code
You're right, the
+character, serving as a quantifier for "one or more" in patterns, causes the issue sinceANIis interpreted as a pattern. You can fix this by first escaping all magic characters inANIusing%signs:ANI:gsub("[][^$()%.*+-?]", "%%%1"). Similarly, you would need to escape%signs inMRPID(which I renamed tonewANI) to avoid them being treated as "capture indices":MRPID:gsub("%%", "%%%%"). This yields:This code is however needlessly complicated; I merely fixed it to demonstrate how to do a literal string replacement in Lua by escaping the arguments of
gsub. Extracted as a function:(you might want to make this a
local functionto not modify thestringtable, which could conflict with other scripts doing the same)