Search code examples
lua

I am looking for a Lua find and replace logic


enter image description here

I just started working on lua scripting since a week. I have a lua file where in the logic needs to be written for a certain condition.

The condition when gets triggered it does an iteration on one of the fields to change value from (ABC123-XYZ) to this value (ABC123#1-XYZ) and it keeps increasing whenever iterations happens (ABC123#2-XYZ)

I need to run a function that removes the # followed by number to change it back to (ABC123-XYZ). Looking for any advice!

Edit 1: Below is the updated code that is written Thanks to @Piglet

I have another scenario if therr are two hashes in the variable.

local x = 'BUS144611111-PNB_00#80901#1555-122TRNHUBUS' 
local b = x:gsub("#%d+","")

function remove_char(a) a=a:gsub("#%d+","") 
return a; 
end if string.match(x,"#")
then print('function') 
print(remove_char(x)); 
else print(x); 
end

Expected output should be x = 'BUS144611111-PNB_00#80901-122TRNHUBUS' for the aforesaid variable


Solution

  • local a = "ABC123#1-XYZ"
    
    local b = a:gsub("#%d+", "")
    

    this will remove any # followed by or one more digits from your string.