String.gsub() capture substring

I have this string,
bind V "echo \"this is a test\" (0, 100, 255)" | blah

And I’m trying to get the whole substring. I want it to look like this:
bind V _ | blah

And I’m using this simple string pattern,
string.gsub(str, "%b\"\"", function(match) substr = match return "_" end)

However, that doesn’t capture the substring correctly. I’ve tried modifying the string pattern and whatnot, and I’ve had no luck. I don’t know how to do this.

the backlash is the issue, its not formatted right, its should be \. Im not sure how you will fix that

i actually made something that “bypasses” the backlash.

local myStr = 'bind V "echo \"this is a test\" (0, 100, 255)" | blah'

local function GetTicks(str,tab,index)
	tab = tab or {}
	
	local var,_ = string.find(str,'"',index or 0)
	
	if var then
		table.insert(tab,var)
		return GetTicks(str,tab,var+1)
	else
		return tab
	end
end

local function gsub2(str,replacement)
	local Ticks = GetTicks(str)
	local charArray = myStr:split("")
	
	local fus1 = str:sub(1,Ticks[1]-1)
	local fus2 = str:sub(Ticks[#Ticks]+1,#str)
	
	return fus1..replacement..fus2
end

local newstr = gsub2(myStr,"_")

print(newstr) -- bind V _ | blah

There is probably other way but thats what i came up with

Tried your script out and it works really well, but I just need it to sub multiple substrings ;(

what I mean is what if there is more than one substring, ex:
bind V "echo \"this is a test\" (0, 100, 255)" | blah "hello world"

I’m super positive there’s a string pattern for this, the closest I’ve gotten to the result was:
%b\"\"[^%b]*
bind V _blah

sorry, I should’ve explained the rules when posting this ;p

1 Like
local Subject = 'bind V "echo \"this is a test\" (0, 100, 255)" | blah'
local Result = string.gsub(Subject, "[^\\]\".*\"[^\\]", " _ ")
print(Result) --bind V _ | blah
1 Like

I managed to fix my problem by replacing all the \" with a placeholder, then replacing all the substrings in the text.

local str = 'bind V "echo \\"this is a test\\" (0, 100, 255)" | blah "hello world"'
local quotes = {}

str = string.gsub(str, "\\\"", "_") print(str)
str = string.gsub(str, "%b\"\"", function(match) table.insert(quotes, match) return "_" end)
for i = 1, #quotes do quotes[i] = string.gsub(quotes[i], "_", "\\\"") end

print(quotes) -- {"echo \"this is a test\" (0, 100, 255)", "hello world"}
print(str) -- bind V _ | blah _

thank you guys for the help though, ig I was too caught up in trying to find a string pattern to fix my problem lol.