Lua: 删除字符串中的特定字符

我有一个包含应在给定字符串中删除的所有字符的字符串。通过嵌套循环,可以遍历两个字符串。但是否有更短的方法?

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  -- 无其他字符可能
      end
    end
    if addChar>0 then new = new..cOrig end
  end
  return new
end

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

ignore 字符串也可以是一个表,如果这可以使代码更短。

点赞
用户2858170
用户2858170

你可以使用string.gsub函数将字符串中给定字符串的所有出现替换为另一个字符串。如果要删除不需要的字符,只需用空字符串替换即可。

local ignore = "'`'"

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

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

请注意,如果要忽略特殊字符,则必须在pattern中转义它们。但我想这会给您一个起点,并留下足够的空间让您完善。

2019-10-28 15:56:12