为什么这个字符串没有拆分成 lua
Why is this string not splitting in lua
所以我正在做一个项目,我需要拆分一个看起来像这样的字符串:
if (x == 2){ 输出("你好") }
这是我的代码:
local function splitIfStatement(str)
local t = {}
t[1] = ""
t[2] = ""
t[3] = ""
local firstSplit = false
local secondSplit = false
local thirdSplit = false
str:gsub(".", function(c)
if c == "(" then
firstSplit = true
end
if firstSplit == true then
if c == "=" then
firstSplit = false
secondSplit = true
else
if c == "(" then
else
t[1] = t[1] .. c
end
end
end
if secondSplit == true then
if c == ")" then
secondSplit = false
thirdSplit = true
else
if c == "=" then
else
t[2] = t[2] .. c
end
end
end
end)
return t
end
我需要在“(”处拆分字符串,因此 t[1] 仅等于“x”,t[2] 等于 2,然后 t[3] 等于“output() “
但是当我 运行 我的代码时(注意我没有添加 t[3]) t[1] returns: "x "Hello") }" 和 t[2 ] returns 2 喜欢它。
无论如何,为什么 split 函数在第一次拆分时不起作用,但在第二次拆分时起作用。
谢谢!
如果输入的形式是
if (AAA == BBB){ CCC("Hello") }
在相关字段周围可能有空格,则此代码有效:
S=[[if (x == 2){ output("Hello") } ]]
a,b,c = S:match('%(%s*(.-)%s.-%s+(.-)%)%s*{%s*(.-)%(')
print(a,b,c)
在你的循环中,如果它命中 (
,你设置 firstSplit
true 这发生在你的示例中的 2 个地方,在 x
之前和 "Hello"
[= 之前19=]
您可以通过在开始循环之前将 firstSplit
设置为 true 并忽略前导 if (
来解决此问题。然后你允许你必须处理其余部分的逻辑。
我还注意到您现在没有任何引用 t[3]
的逻辑。
所有这些都表明您确实应该使用模式来解析类似这样的内容。
local function splitIfStatement(str)
t = {str:match("if%s*%((%w+)%s*[=<>]+%s*(%d+)%)%s*{(.+)}")}
return t
end
此模式非常狭窄,需要特定类型的 if 语句,您可以在此处了解有关 lua 模式的更多信息:Understanding Lua Patterns
所以我正在做一个项目,我需要拆分一个看起来像这样的字符串:
if (x == 2){ 输出("你好") }
这是我的代码:
local function splitIfStatement(str)
local t = {}
t[1] = ""
t[2] = ""
t[3] = ""
local firstSplit = false
local secondSplit = false
local thirdSplit = false
str:gsub(".", function(c)
if c == "(" then
firstSplit = true
end
if firstSplit == true then
if c == "=" then
firstSplit = false
secondSplit = true
else
if c == "(" then
else
t[1] = t[1] .. c
end
end
end
if secondSplit == true then
if c == ")" then
secondSplit = false
thirdSplit = true
else
if c == "=" then
else
t[2] = t[2] .. c
end
end
end
end)
return t
end
我需要在“(”处拆分字符串,因此 t[1] 仅等于“x”,t[2] 等于 2,然后 t[3] 等于“output() “
但是当我 运行 我的代码时(注意我没有添加 t[3]) t[1] returns: "x "Hello") }" 和 t[2 ] returns 2 喜欢它。
无论如何,为什么 split 函数在第一次拆分时不起作用,但在第二次拆分时起作用。
谢谢!
如果输入的形式是
if (AAA == BBB){ CCC("Hello") }
在相关字段周围可能有空格,则此代码有效:
S=[[if (x == 2){ output("Hello") } ]]
a,b,c = S:match('%(%s*(.-)%s.-%s+(.-)%)%s*{%s*(.-)%(')
print(a,b,c)
在你的循环中,如果它命中 (
,你设置 firstSplit
true 这发生在你的示例中的 2 个地方,在 x
之前和 "Hello"
[= 之前19=]
您可以通过在开始循环之前将 firstSplit
设置为 true 并忽略前导 if (
来解决此问题。然后你允许你必须处理其余部分的逻辑。
我还注意到您现在没有任何引用 t[3]
的逻辑。
所有这些都表明您确实应该使用模式来解析类似这样的内容。
local function splitIfStatement(str)
t = {str:match("if%s*%((%w+)%s*[=<>]+%s*(%d+)%)%s*{(.+)}")}
return t
end
此模式非常狭窄,需要特定类型的 if 语句,您可以在此处了解有关 lua 模式的更多信息:Understanding Lua Patterns