How would I add "-" every 4 letters?

How would I add “-” every 4 letters?

I probably have to use gsub but I’m not sure how to do it.

Example:
IUGBUZPMHTHBRFYG

would become:
IUGB-UZPM-HTHB-RFYG

local strings = "IUGBUZPMHTHBRFYG"
strings = strings:gsub("(....)", "%1-")
strings = strings:gsub("-$", "")
print(strings) --IUGB-UZPM-HTHB-RFYG
4 Likes
local strings = "IUGBUZPMHTHBRFYG"
local result = ""
local count = 0

for char in strings:gmatch(".") do
	count += 1
	result..=char
	if (count % 4 == 0) and (count ~= #strings) then
		result..="-"
	end
end

print(result) --IUGB-UZPM-HTHB-RFYG
2 Likes

Pretty easy to do, here’s an adjustable version.

local OurString = "IUGBUZPMHTHBRFYG"

local function Hyphenate(String, Per, Clean)
	Per = if Per then Per else 4
	if Clean then String = string.gsub(String, "%p", "") end -- Remove all prior punctuation.
	local Buffer, Temp = table.create(math.ceil(#String / Per)), ""
	for Ptr in string.gmatch(String, ".") do
		Temp ..= Ptr
		if #Temp == Per then
			table.insert(Buffer, Temp)
			Temp = ""
		end
	end
	if Temp ~= "" then
		table.insert(Buffer, Temp)
	end
  return table.concat(Buffer, "-")
end

print(Hyphenate(OurString, 4))
print(Hyphenate(OurString, 8))
print(Hyphenate(OurString .. "AB", 4))

Edit: Changed it a bit, added “Clean” to remove prior punctuation if you wish. As well as changed from alphanumeric “%a” to any character “.”

2 Likes

You could also modify @Forummer 's solution to achieve the same result.

local function adjust(myString, numGroup)
  local hyphenated = string.gsub(string.gsub(myString, string.format("(%s)", string.rep(".", numGroup)), "%1-"), "-$", "")
  return hyphenated
end