How to get the length of a string capture?

Hello,
I’m making a function to simplify the pattern of #("string") into its actual number (6 in this case). This is what I have right now:

local function SimplifyStrings(str)
	return str:gsub(
		"#%(\"(.+)\"%)",
		string.len("%1")
	)
end

print(SimplifyStrings("#(\"does it work?\")"))

The problem here is that it pre-processes the length of %1 to a 2. How could I get around this issue?
(No, changing string.len to # doesn’t help)

1 Like

You should use string.match instead. Which will return the string which matches our pattern, then we can just get the length of it using the # operator

local function SimplifyStrings(str)
   return #str:match("#%(\"(.+)\"%)$")
end

print(SimplifyStrings("#(\"does it work?\")")) -- 13
print(SimplifyStrings("#(\"string\")")) -- 6

Yes, but I want it to replace more occurrences than 1. In my case when I use it there will probably be around 50 of these.

I’m not sure if this is exactly what you wanted, and im also not the best at string patterns so there is probably a more elegant solution

But here is what I got…

local function SimplifyStrings(str)
	local sum = "";
	for w in str:gmatch("[^#%(\"(.+)\"%)]+") do
		sum ..= string.len(w) .. " "
	end
	return sum
end

print(SimplifyStrings("#(\"string\")#(\"does it work?\")")) -- 6 13
1 Like

Yeah this works good, but I also want it to keep other things that don’t match the pattern.

Update: I got it to work.

local function SimplifyStrings(String)
	for capture in string.gmatch(String, "#%(\"([^\"]+)") do
		String = String:gsub(
			"#%(\"([^\"]+)\"%)",
			#capture,
			1
		)
	end
	
	return String
end

print(SimplifyStrings(
	"#(\"Did it work?\") some strings in between #(\"Yes it did!\")"
))

Output:
12 some strings in between 11