Search code examples
stringlualua-patterns

Lua patterns to replace multiple semicolons


I got this string in a Lua script:

one;two;;three;four;;five;;six;seven;

The first char will never be a semicolon. The middle separators can be a single or double semicolon, and the last char can be or not a single semicolon.

Using the Lua patterns (and string.gsub()): How can I match the double semicolons in the middle to replace those with a single one AND delete the last optional semicolon?

The output must be like this:

one;two;three;four;five;six;seven

Is this possible using a single pattern?


Solution

  • Using one pattern to replace multiple ; to single ;, and another to remove the last ; is like this

    local str = "one;two;;three;four;;five;;six;seven;"
    local result = str:gsub(';+', ';'):gsub(';*$', '')
    

    One possible way to use a single pattern is like this:

    local result = (str .. ";;;"):gsub(";+", function(s) 
                                                 if s == ";" or s == ";;" then 
                                                     return ";" 
                                                 else 
                                                     return "" 
                                                 end 
                                             end)
    

    What I'm trying to do is to append three ; to the end of the string, so any one or two ; should be replaced with one ;. And more ;(could be three or four and it must be at the end) is replaced to empty string.

    I would prefer the solution with two patterns as it's more clear.