3

I have a string with a set of delimited tokens that looks something like this:

local str = "foo;bar;baz"

I'd like to be able to accurately tell if a given token is in this string or not:

in_str("foo", str) -- true
in_str("bar", str) -- true
in_str("baz", str) -- true
in_str("ba", str) -- false
in_str("foo;", str) -- false

Using PHP and regular expressions, I would accomplish the desired effect with something like this:

function in_str($needle, $haystack) {
    return (bool)preg_match('/(^|;)' . preg_quote($needle, '/') . '(;|$)/', $haystack);
}

I'm unsure how to translate this logic into Lua, though. I'd also rather be able to do it in vanilla Lua, without any plugins/extensions/etc. I'd also like it to be reasonably efficient. The only way I've managed to implement this correctly thus far involves splitting the string into a table, and then iterating it, which is obviously very inefficient.

4

2 に答える 2

4

作業中のコードのサンプルは次のとおりです: LINK

local str = "foo;bar;baz;and;some;more;random;data;in;here"
function check(sString, sData)
  print( string.find(";"..sString..";", ";"..sData..";") )
end
check( str, "foo" )
check( str, "bar" )
check( str, "ba" )
check( str, "baz" )
check( str, "random" )
check( str, "stuff" )
于 2012-07-15T19:14:20.283 に答える
1

Lua のパターンマッチ API には (論理 OR) 演算子がないため|、代わりに次のようにすることができます。

function in_str(needle, haystack)
  return (haystack:find(';' .. needle .. ';') or
          haystack:find('^' .. needle .. ';') or
          haystack:find(';' .. needle .. '$')) ~= nil
end

local str = "foo;bar;baz"

print(in_str("foo", str))  -- true
print(in_str("bar", str))  -- true
print(in_str("baz", str))  -- true
print(in_str("ba", str))   -- false
print(in_str("foo;", str)) -- false
于 2012-07-15T19:16:37.400 に答える