I'm attempting to parse some output from CMake, but I keep getting nil when I attempt to loop over all the matches.
local s = [[Available configure presets:
"x64-debug" - x64 Debug
"x64-release" - x64 Release
"x86-debug" - x86 Debug
"x86-release" - x86 Release]]
for word in string.gmatch(s, [["(.*?)"\s{1,}-\s{1,}(.*)]]) do
print(word)
end
Expected output:
x64-debug
x64 Debug
x64-release
x64 Release
...
I'm not sure if I'm misunderstanding how string.gmatch works, or if my regex is just wrong for whatever flavor Lua uses (it seems to work for PHP: https://regex101.com/r/jP3jBk/1)
Here's the regex: "(.*?)"\s{1,}-\s{1,}(.*)
You are trying to use regular expression instead of a Lua pattern with gmatch
, which is a problem. Just FYI:
.*?
- is a non-greedy pattern that looks like (almost) .-
in Lua patterns (the difference is that .
in Lua matches ALL characters including newline and carriage returns, while in regex, it needs specific option to enable matching line breaks)\s
- a whitespace matching pattern looks like %s
in Lus patterns{1,}
- one or more repetition must be written as +
in Lua patterns, as limiting quantifiers are not supported.You can use
"(.-)"%s+-%s
NOTE: I removed the last (.*)
because you only need the part in between the double quotes, and the .*
will simply capture all text after the first double quoted substring.
Details
"
- a "
char(.-)
- Capturing group 1: any zero or more chars (including line break chars), as few as possible"
- a "
char%s+
- one or more whitespace chars-
- a hyphen%s
- a whitespace char.See the online Lua demo:
local s = [[Available configure presets:
"x64-debug" - x64 Debug
"x64-release" - x64 Release
"x86-debug" - x86 Debug
"x86-release" - x86 Release]]
for word in string.gmatch(s, [["(.-)"%s+-%s]]) do
print(word)
end
Output:
x64-debug
x64-release
x86-debug
x86-release
Now, if you need the part after -
, you can simply match any chars as few as possible till the newline after appending a newline to your input string:
for word1,word2 in string.gmatch(s .. string.char(10), [["(.-)"%s+-%s(.-)]] .. string.char(10)) do
print(word1 .. " <> " .. word2)
end
See this Lua demo:
local s = [[Available configure presets:
"x64-debug" - x64 Debug
"x64-release" - x64 Release
"x86-debug" - x86 Debug
"x86-release" - x86 Release]]
for word1,word2 in string.gmatch(s .. string.char(10), [["(.-)"%s+-%s(.-)]] .. string.char(10)) do
print(word1 .. " <> " .. word2)
end
Output:
x64-debug <> x64 Debug
x64-release <> x64 Release
x86-debug <> x86 Debug
x86-release <> x86 Release