lemonowo
lemonowo

Reputation: 45

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

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:

"?"   =  "?"
"??"  =  "?-?"
"???  =  "?-?-?"

Upvotes: 2

Views: 262

Answers (3)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7066

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???"))

Upvotes: 1

Foxie Flakey
Foxie Flakey

Reputation: 420

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

Upvotes: -1

lhf
lhf

Reputation: 72312

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

Upvotes: 3

Related Questions