I have a table of values, and I am iterating through the table and attempting to separate each value into two parts. The values go like this: "Name | Number". I am trying to use string.match to separate them, but it isn't working.
Script:
for i = 1, #StatsData do local pattern = "(%a+)$a?|%s?(%d+)" print(StatsData[i]) local key1, val1 = string.match(StatsData[i], pattern) print(key1, val1) --prints "nil, nil" end
Thank you!
Namaste it is, dual
First of all, you have to realise 1 thing - string.match()
does NOT return 2, 3, 4 or n
things. It returns 1 thing. One. This can be found here:
https://developer.roblox.com/api-reference/lua-docs/string.
"If a match is found, it is returned"
Next, you should use an i,v pair
loop. What you're doing now is more efficient than said loop, so yes it's more optimised, however it's evident you don't need this optimisation more than you need readability. I recommend rewriting this loop with an i,v pair
loop.
Second, can you give an example of the array's values? Right now I'm using {"dlp | 1", "sin | 2", "viking | 3"}
, and my code works with this.
I would also like to mention your pattern has a lot of redundant things, that you're also using wrong. lol(?). I recommend reading more about Lua RegEx/pattern matching on: http://lua-users.org/wiki/PatternsTutorial
Here is some reformatted code I wrote.
local arr = {"dlp | 1", "sin | 2", "viking | 3"} for _, v in pairs(arr) do -- Use a i, v pair loop. I'm not sure why you're using `[i]` local match_name = "(%a+)" -- A `^` at the start of the pattern is not needed as there is only 1 alphanumeric value in the string. local match_number = "(%d)" -- A `$` at the end of the pattern is not needed as there is only 1 integer in the string. local matched_name, matched_number = string.match(v, match_name), string.match(v, match_number) print(matched_name, matched_number) -- Prints what you want. end
That is all