Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: delete specific characters in a string

I have a string that includes all the characters which should be deleted in a given string. With a nested loop I can iterate through both strings. But is there a shorter way?

local ignore = "'`'"  

function ignoreLetters( c )
  local new = ""
  for cOrig in string.gmatch(c,".") do
    local addChar = 1
    for cIgnore in string.gmatch(ignore,".") do
      if cOrig == cIgnore then
        addChar = 0
        break  -- no other char possible
      end
    end
    if addChar>0 then new = new..cOrig end
  end
  return new
end

print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))

The string ignore can also be a table if it makes the code shorter.

like image 511
Red-Cloud Avatar asked Nov 30 '25 07:11

Red-Cloud


1 Answers

You can use string.gsub to replace any occurance of a given string in a string by another string. To delete the unwanted characters, simply replace them with an empty string.

local ignore = "'`'"  

function ignoreLetters( c )
  return (c:gsub("["..ignore.."]+", ""))
end

print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))

Just be aware that in case you want to ignore magic characters you'll have to escape them in your pattern. But I guess this will give you a starting point and leave you plenty of own work to perfect.

like image 131
Piglet Avatar answered Dec 02 '25 22:12

Piglet