How to check this line if we don't have the `|` operator in Lua?

I have form lines:

cake!apple!

apple!

cake!juice!apple!cake!

juice!cake!

In other words, these lines consist of three substrings "cake!", "apple!"and "juice!".

I need to check these lines. Thus, using a regular expression, you can:

/^(apple!|juice!|cake!)*$/

But Lua templates do not have an operator |, so it seems like you can't do it this way.

How can I check my lines in Lua?

(I'm not interested in the contents of the strings: I don't care if they match (check) or not.)

I know to write code to do this, but I can't think of a short way to do this. I am looking for a short solution. I wonder if there is an elegant solution that I don't know about. Any ideas?

+4
7
if str:gsub("%w+!", {["apple!"]="", ["juice!"]="", ["cake!"]=""}) == "" then
    --do something
end

string.gsub. %w+, , . , .

:

local t = {["apple!"]="", ["juice!"]="", ["cake!"]=""}
if str:gsub("%w+!", t) == "" then
    --do something
end
+5

, , , "\1" (ASCII 1) , :

local str = "cake!juice!apple!cake!"
if str:gsub("apple!","\1"):gsub("juice!","\1"):gsub("cake!","\1"):gsub("\1","") == "" then
    --do something
end

"\1" , , "\1" , ​​.

( , ), , .

+2

, , ().

local strs = {
    "cake!apple!",
    "bad",
    "apple!",
    "apple!bad",
    " apple!bad",
    "cake!juice!apple!cake!",
    "cake!juice! apple!cake!",
    "cake!juice!badapple!cake!",
    "juice!cake!",
    "badjuice!cake!",
}

local legalwords = {
    ["cake!"] = true,
    ["apple!"] = true,
    ["juice!"] = true,
}

local function str_valid(str)
    local newpos = 1
    for pos, m in str:gmatch("()([^!]+!)") do
        if not legalwords[m] then
            return
        end
        newpos = pos + m:len()
    end
    if newpos ~= (str:len() + 1) then
        return nil
    end

    return true
end

for _, str in ipairs(strs) do
    if str_valid(str) then
        print("Match: "..str)
    else
        print("Did not match: "..str)
    end
end
+1

, lpeg re module:

re = require 're'

local testdata =
{
  "cake!apple!",
  "apple!",
  "cake!juice!apple!cake!",
  "cake!juice!badbeef!apple!cake!",
  "juice!cake!",
  "badfood",
}

for _, each in ipairs(testdata) do
  print(re.match(each, "('cake!' / 'apple!' / 'juice!')*") == #each + 1)
end

:

true
true
true
false
true
false

^ $, , lpeg matching .

+1

Lua . , , , , , .

0

- :

local words = {cake=1,apple=2,juice=3}
local totals = {}
local matches = 0
local invalid = 0
string.gsub("cake!","(%a+)!",
   function(word)
      local index = words[word]
      if index then
         matches = matches + 1
         totals[index] = totals[index] + 1
      else
         invalid = invalid + 1
      end
   end
)

if matches > 0 and invalid == 0 then
   -- Do stuff
end

, .

0
source

I don’t know if it will help you solve your problem. But using string.find (), I could use " or ". see:

str="juice!"

print(string.find(str, "cake!" or "teste"))

Regards

-3
source

All Articles