I'm sorry to say that I have no clue how I would do this. I apologize for not being able to post any code. So how do I find text before a certain character? if i was trying to find the text before "/" then
ex: hiy1o/meyo:939a:a output: hiy1o
ex:asi2w5/uiqwt:tueja:rs output: asi2w5
The :find
method finds the first occurrence of a pattern in a string (or nil
if there isn't one).
To get everything before a /
we can just find
the /
and take the sub
tring of everything before and after it.
str = "hiy1o/meyo:939a:a" slashPos = str:find("/") if slashPos then -- Found a / before = str:sub(1, slashPos - 1) -- hiy1o after = str:sub(slashPos + 1) -- meyo:939a:a else -- No "/" in str -- (slashPos is nil) end
Alternatively, we can use match
. It returns the matching parts of patterns contained in parenthesis.
str = "hiy1o/meyo:939a:a" notSlash = "[^/]*" -- a list of at least 0 not-slash characters anything = ".*" -- a list of any characters matcher = "(" .. notSlash .. ")" .. "/" .. "(" .. anything.. ")" -- Pattern separated for clarity. Equivalent to this: -- "([^/]*)/(.*)" before, after = str:match( matcher ) if before then -- There was a slash -- before: "hiy1o" -- after: "meyo:939a:a" else -- No slash end
Note: because I use *
instead of +
in my patterns, this will match things without anything before & after the slash. If you want to require there be things before and after, change the corresponding * to a + (with +, if nothing was typed, the match will fail and instead only return nil
s)