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.
Here's a sample of the code at work: 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" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With