Lua string.match() problem
I want to match a few lines for a string and a few numbers. The lines can look like
" Code : 75.570 "
or
" ..dll : 13.559 1"
or
" ..node 开发者_JAVA技巧 : 4.435 1.833 5461"
or
" ..NavRegions : 0.000 "
I want something like
local name, numberLeft, numberCenter, numberRight = line:match("regex");
But I'm very new to the string matching.
This pattern will work for every case:
%s*([%w%.]+)%s*:%s*([%d%.]+)%s*([%d%.]*)%s*([%d%.]*)
Short explanation: []
makes a set of characters (for example the decimals). The last to numbers use [set]*
so an empty match is valid too. This way the number that haven't been found will effectively be assigned nil
.
Note the difference between using +
-
*
in patterns. More about patterns in the Lua reference.
This will match any combination of dots and decimals, so it might be useful to try and convert it to a number with tonumber()
afterwards.
Some test code:
s={
" Code : 75.570 ",
" ..dll : 13.559 1",
" ..node : 4.435 1.833 5461",
" ..NavRegions : 0.000 "
}
for k,v in pairs(s) do
print(v:match('%s*([%w%.]+)%s*:%s*([%d%.]+)%s*([%d%.]*)%s*([%d%.]*)'))
end
Here is a starting point:
s=" ..dll : 13.559 1"
for w in s:gmatch("%S+") do
print(w)
end
You may save these words in a table instead of printing, of course. And skip the second word.
@Ihf Thank you, I now have a working solution.
local moduleInfo, name = {};
for word in line:gmatch("%S+") do
if (word~=":") then
word = word:gsub(":", "");
local number = tonumber(word);
if (number) then
moduleInfo[#moduleInfo+1] = number;
else
if (name) then
name = name.." "..word:gsub("%$", "");
else
name = word:gsub("%$", "");
end
end
end
end
@jpjacobs Really nice, thanks too. I'll rewrite my code for synthetic reasons ;-) I'll implement your regex of course.
I have no understanding of the Lua language, so I won't help you there. But in Java this regex should match your input
"([a-z]*)\\s+:\\s+([\\.\\d]*)?\\s+([\\.\\d]*)?\\s+([\\.\\d]*)?"
You have to test each group to know if there is data left, center, right
Having a look at Lua, it could look like this. No guarantee, I did not see how to escape .
(dot) which has a special meaning and also not if ?
is usable in Lua.
"([a-z]*)%s+:%s+([%.%d]*)?%s+([%.%d]*)?%s+([%.%d]*)?"
精彩评论