string - 我将如何撤消 string.gmatch 对 lua 中某个字符串部分的操作
问题描述
所以我使用 lua 并用空格分割字符串来编写一种子语言。而且我试图让它不分裂括号内的任何东西,我已经处于可以检测是否有括号的阶段。但是我想反转括号内字符串的 gmatching,因为我想保留其中包含的字符串。
local function split(strng)
local __s={}
local all_included={}
local flag_table={}
local uncompiled={}
local flagged=false
local flagnum=0
local c=0
for i in string.gmatch(strng,'%S+') do
c=c+1
table.insert(all_included,i)
if(flagged==false)then
if(string.find(i,'%('or'%['or'%{'))then
flagged=true
flag_table[tostring(c)]=1
table.insert(uncompiled,i)
print'flagged'
else
table.insert(__s,i)
end
elseif(flagged==true)then
table.insert(uncompiled,i)
if(string.find(i,'%)' or '%]' or '%}'))then
flagged=false
local __=''
for i=1,#uncompiled do
__=__ .. uncompiled[i]
end
table.insert(__s,__)
print'unflagged'
end
end
end
return __s;
end
这是我的拆分代码
解决方案
我根本不会用gmatch
这个。
local input = " this is a string (containg some (well, many) annoying) parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? "
local pos = 1
local words = {}
local last_start = pos
while pos <= #input do
local char = string.byte(input, pos)
if char == string.byte(" ") then
table.insert(words, string.sub(input, last_start, pos - 1))
last_start = pos + 1
elseif char == string.byte("(") then
local depth = 1
while depth ~= 0 and pos + 1 < #input do
local char = string.byte(input, pos + 1)
if char == string.byte(")") then
depth = depth - 1
elseif char == string.byte("(") then
depth = depth + 1
end
pos = pos + 1
end
end
pos = pos + 1
end
table.insert(words, string.sub(input, last_start))
for k, v in pairs(words) do
print(k, "'" .. v .. "'")
end
输出:
1 ''
2 'this'
3 'is'
4 'a'
5 'string'
6 '(containg some (well, many) annoying)'
7 'parentheses'
8 'and'
9 'should'
10 'be'
11 'split.'
12 'The'
13 'string'
14 'contains'
15 ''
16 'double'
17 ''
18 ''
19 'spaces.'
20 'What'
21 'should'
22 'be'
23 'done?'
24 'And'
25 'what'
26 'about'
27 'trailing'
28 'spaces?'
29 ''
思考尾随空格和其他此类问题留给读者作为练习。我试图强调我使用的示例可能存在的一些问题。另外,我只看了一种括号,因为我不想思考如何this (string} should be ]parsed
。
哦,如果不关心嵌套括号:上面的大部分代码都可以替换为调用string.find(input, ")", pos, true)
来查找右括号。
请注意,您不能or
或and
在您的代码中尝试的模式。
"%(" or "%["
等于"%("
Lua 会从左到右解释这个表达式。"%(
是一个真值 Lua 会将表达式简化为"%("
,这在逻辑上与完整表达式相同。
所以string.find(i,'%('or'%['or'%{')
只会find (
's in i
。
推荐阅读
- oracle - 准备好的语句-执行批处理,即使一行有错误,整个批处理也会失败
- azure - Azure - npm 不是公认的命令
- c# - 使用 Carter 框架发送到我的网络服务的图像始终为空
- android - 串行或并行:机器人测试实验室的设备测试订单
- c# - 安装的 nuget 包缺少文件
- python - 如何找到字符串中的所有Occurance
- java - Docker-compose 与 MySql 的容器连接不起作用
- javascript - 当我单击关闭表单的按钮时,为什么我的 HTML 网页会刷新
- visual-studio-2017 - VS2017 - 尝试将 nuget 包保存到 Xamarin 文件夹中 - 为什么?
- neo4j - 与 Cypher 中的聚合函数 min() 匹配最短距离