I'm trying to use string.find
in Lua to parse the contents of a user-entered string. There are up to three different parameters I am trying to find (if the user enters them), but sometimes only one.
The input string in its longer form looks like:
local userInput = "x|y|z"
where x
, y
, and z
can be any character or nothing (empty string, i.e. ""
) and
z
can also contain vertical bars/pipes - I only want to divide the string into three sections based on the first two vertical bars ("|"
) encountered. The difficulty is that the user can also not use that form - he or she can enter simply "x"
or "x||z"
or "||z"
, etc. In these case I would still need to get the values of x
, y
, and z
, and it should be clear as to which variables they were assigned to.
For example, I tried this:
local _,_,a,b,c = string.find(usermsg, "([^|]*)|?([^|]*)|?(.+)")
Note first of all that this doesn't even properly fetch a
, b
, and c
properly. But more importantly, when the usermsg
was just "x"
, it set the value of x
to variable c
, when it should be a
. And when the user types "x|y"
, variable a
is x
(correct) but variable c
is y
(wrong, it should be assigned to variable b
).
So then I tried doing it separately:
local _,_,a = string.find(usermsg , "([^|]+)|?[^|]*|?.*") local _,_,b= string.find(usermsg , "[^|]*|([^|]+)|?.*") local _,_,c= string.find(usermsg , "[^|]*|[^|]*|(.+)")
But this also fails. It matches x
, but not y
, and c
ends up being y
plus the pipe and z
.
Any help would be appreciated. Thanks! :)