Lua: How do I place something between two or more repeating characters in a string?

Viewed 144

This question is somewhat similar to this, but my task is to place something, in my case the dash, between the repeating characters, for example the question marks, using the gsub function.

Example:

"?"   =  "?"
"??"  =  "?-?"
"???  =  "?-?-?"
3 Answers

Try this:

function test(s)
    local t=s:gsub("%?%?","?-?"):gsub("%?%?","?-?")
    print(#s,s,t)
end

for n=0,10 do
    test(string.rep("?",n))
end

A possible solution using LPeg:

local lpeg = require 'lpeg'

local head = lpeg.C(lpeg.P'?')
local tail = (lpeg.P'?' / function() return '-?' end) ^ 0

local str = lpeg.Cs((head * tail + lpeg.P(1)) ^ 1)

for n=0,10 do
    print(str:match(string.rep("?",n)))
end

print(str:match("?????foobar???foo?bar???"))

This what i can came out with scanning each letter by letter

function test(str)
  local output = ""
  local tab = {}
  for let in string.gmatch(str, ".") do
    table.insert(tab, let)
  end
  local i = 1
  while i <= #tab do
    if tab[i - 1] == tab[i] then
      output = output.."-"..tab[i]
    else
      output = output..tab[i]
    end
    i = i + 1
  end
  return output
end
for n=0,10 do
  print(test(string.rep("?",n)))
end
Related