Red-Cloud
Red-Cloud

Reputation: 458

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.

Upvotes: 3

Views: 1873

Answers (1)

Piglet
Piglet

Reputation: 28994

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.

Upvotes: 4

Related Questions