String 模式匹配与Lua';s字符串模块
我正在尝试使用Lua中的String 模式匹配与Lua';s字符串模块,string,lua,find,design-patterns,String,Lua,Find,Design Patterns,我正在尝试使用Lua中的string.find来解析用户输入的字符串的内容。我尝试查找最多三个不同的参数(如果用户输入),但有时只有一个 较长形式的输入字符串如下所示: local userInput = "x|y|z" 首先请注意,这甚至不能正确地获取a、b和c。但更重要的是,当usermsg仅为“x”时,它将x的值设置为变量c,而该值应为a。当用户键入“x | y”时,变量a为x(正确),而变量c为y(错误,应将其分配给变量b) 然后我试着分开做: local _,_,a = string.
string.find
来解析用户输入的字符串的内容。我尝试查找最多三个不同的参数(如果用户输入),但有时只有一个
较长形式的输入字符串如下所示:
local userInput = "x|y|z"
首先请注意,这甚至不能正确地获取a
、b
和c
。但更重要的是,当usermsg
仅为“x”
时,它将x
的值设置为变量c
,而该值应为a
。当用户键入“x | y”
时,变量a
为x
(正确),而变量c
为y
(错误,应将其分配给变量b
)
然后我试着分开做:
local _,_,a = string.find(usermsg , "([^|]+)|?[^|]*|?.*")
local _,_,b= string.find(usermsg , "[^|]*|([^|]+)|?.*")
local _,_,c= string.find(usermsg , "[^|]*|[^|]*|(.+)")
local u,u,a=string.find(usermsg,“([^ |]+)|?[^ |]*|?.*”)
local u,u,b=string.find(usermsg,“[^ |]*|”([^ |]+)|?.*))
local u,u,c=string.find(usermsg,[^ |]*.[^ |]*.+]))
但这也失败了。它匹配x
,但不匹配y
,c
最后是y
加上管道和z
任何帮助都将不胜感激。谢谢!:) 这应该按照您的意愿工作
local _,_,a,b = string.find(usermsg, "([^|]*)|?(.*)")
local _,_,b,c = string.find(b, "([^|]*)|?(.*)")
似乎您只需要查找具有最大拆分数的典型拆分函数。这是我的:
function string.split( str, delim, max, special )
if max == nil then max = -1 end
if delim == nil then delim = " " end
if special == nil then special = False end
local last, start, stop = 1
local result = {}
while max ~= 0 do
start, stop = str:find(delim, last, not special )
if start == nil then
-- if max > #(all ocurances of delim in str), we end here
break
end
table.insert( result, str:sub( last, start-1 ) )
last = stop+1
max = max - 1
end
-- add the rest
table.insert( result, str:sub( last ) )
return result
end
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello|there|world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("||world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello||world"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello|there|"):split('|', 2) )))
print( ("A='%s' B='%s' C='%s'"):format(unpack( ("hello||world|and|the|rest"):split('|', 2) )))
=>
我认为解决这个问题的最好办法是
string.match
local a, b, c = string.match( "(^|*)|(^|*)|(.*)" )
^ |
匹配任何非|
的内容,而*
意味着它将匹配0或更多。如果用户输入为“a | b | c”,返回a=“a”b=“a”c=“| b | c”您使用的LUA是什么版本?我正在v5.1.4上测试它,它返回了预期的值。
A='hello' B='there' C='world'
A='' B='' C='world'
A='hello' B='' C='world'
A='hello' B='there' C=''
A='hello' B='' C='world|and|the|rest'
local a, b, c = string.match( "(^|*)|(^|*)|(.*)" )