r/lua • u/GAS4z0t • Jun 13 '26
Help `string.find` produces unexpected results
I'm doing some basic string matching and this code produces unexpected results.
---@param levels string?
---@return boolean
local
if type(levels) \~= "string" then
return false
end
local pattern = "\^\[a-zA-Z_\]\[a-zA-Z0-9_\]\*(%.\[a-zA-Z_\]\[a-zA-Z0-9_\]\*)\*$"
return levels:find(pattern) \~= nil
end
print(IsValidLevels("my.levels")) -- true
print(IsValidLevels("my.more.levels")) -- true
print(IsValidLevels("foo")) -- true
print(IsValidLevels("a.b.c.d")) -- true
print(IsValidLevels(".invalid")) -- false
print(IsValidLevels("invalid.")) -- false
print(IsValidLevels("ReUI..Score")) -- false
print(IsValidLevels("123invalid")) -- false
But in result I get all `false`. What is the problem?
5
Upvotes
5
u/Cootshk Jun 13 '26
Lua doesn’t use Regex, instead it uses its own [pattern](https://www.lua.org/manual/5.4/manual.html#6.4.1) system
6
u/SoloMaker Jun 13 '26
The * after the capture group is either a mistake or doesn't work the way you think it does (here it's looking for a * literal.)
3
u/xoner2 Jun 14 '26
Parentheses are for captures, they don't group. You'll need to use one of: lpeg, regex library (lrexlib), string.gmatch.
1
u/AutoModerator Jun 13 '26
Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Old_County5271 Jun 22 '26
can be simplified to
Your problem is you did ()*, which is not a thing in luapatterns or even basic regex, its only a thing in extended regex and perl regex. Even if it did work, this would always return true not nil.
1
u/[deleted] Jun 13 '26
[removed] — view removed comment