Search code examples
lualua-patterns

Match string until a character or end


I'm trying to match and return a string between two (or one if there's no closing character, then until the string's end) character.

local id = "+@a-@s,@n";

local addOperator = string.match(id, "^[+](.+)(?[-])"); -- should return "@a"
if (addOperator) then 
   -- ...
end

local removeOperator = string.match(id, "^[-](.+)(?[+])"); -- should return "@s,@n"
if (removeOperator) then 
   -- ...
end 

-- Or without the excluding operator "-" 

local id = "+@a";

local addOperator = string.match(id, "^[+](.+)(?[-])"); -- should return "@a", with my pattern it returns a nil.
if (addOperator) then 
   -- ...
end

Solution

  • ? should come after the char you are matching 0 to 1 of. You also can not use .+ followed by any char ? and expect the ? to restrict the results of the .+

    I suggest using an a set that excludes -. Additionally you use [+] but should be using %+, % is how you escape a special character in a pattern. Using [+] to escape is not necessarily wrong functionally it just comes off as odd or non-idiomatic in Lua.

    local id = "+@a-@s,@n"
    print(string.match(id, "^%+([^-]+)"))
    print(string.match(id, "%-(.+)"))
    
    id = "+@a"
    print(string.match(id, "^%+([^-]+)"))
    

    This is a good resource for understanding Lua patters: Understanding Lua Patterns