Combine multiple string.match functions into a single line

1.5k views Asked by At

I have a function where I need to check for special characters and break it if I find one.

Here is what I have tried.

local text = "h!ello\"wor%[email protected]^*sp&ki#$te"

if (string.match(text, "&") ~= nil) then
  print("Invalid Character \n")
end 

if (string.match(text, "\"") ~= nil) then
  print("Invalid Character \n")
end 

if (string.match(text, "#") ~= nil) then
  print("Invalid Character \n")
end 

if (string.match(text, "$") ~= nil) then
  print("Invalid Character \n")
end 

if (string.match(text, "@") ~= nil) then
  print("Invalid Character \n")
end

if (string.match(text, "%%") ~= nil) then
  print("Invalid Character \n")
end

if (string.match(text, "!") ~= nil) then
  print("Invalid Character \n")
end

if (string.match(text, "^") ~= nil) then
  print("Invalid Character \n")
end

if (string.match(text, "*") ~= nil) then
  print("Invalid Character \n")
end

I'm able to successfully do this, but I want everything in single line. Went through Lua Programming book but couldn't get.

2

There are 2 answers

2
Etan Reisner On BEST ANSWER

To match on one of a set of characters you need to use the [set] notation1.

So the following should do what you want and provide a slightly better indication of the failure:

local p = string.find(text, '[&"#$@%%!^*]');

if p then
    print("Invalid character found at "..p)
end

You could even include the exact character that failed:

print("Invalid character '"..text:sub(p,p).."' at position "..p)
0
Yu Hao On

Like this:

if text:match '[&"#$@%%!^*]' then 
  print 'Invalid Character'
end