Skip to content

Instantly share code, notes, and snippets.

@Buy-One
Created June 13, 2022 09:48
Show Gist options
  • Save Buy-One/89cb56467e53b271ce2449f5c4622654 to your computer and use it in GitHub Desktop.
Save Buy-One/89cb56467e53b271ce2449f5c4622654 to your computer and use it in GitHub Desktop.
Replace Nth capture
function replace_Nth_capture(src_str,capt,repl_str,N)
-- 1. if not N then N is 1
-- 2. if no captures or N is 0 or greater than the number of captures returns original string
-- if the 3d arg (repl_str) isn't a string then returns orig string and boolean to indicate no changes
local N = N and tonumber(N) and math.abs(math.floor(N)) -- validate N
if not N then N = 1 end
local cntr = 0
local str_new = ''
if repl_str and not type(repl_str) then return str, false end
for w1, w2 in src_str:gmatch('(%w*)([%p%s%c]*)') do
cntr = (N ~= cntr and w1 == capt or N == cntr) and cntr+1 or cntr
if N == cntr then w1, w2 = repl_str..w2, '' end
str_new = str_new..w1..w2
end
return str_new, str ~= str_new -- 2nd val is boolean showing if any changes were made
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment