Created
June 13, 2022 09:49
-
-
Save Buy-One/ed5f569fa32f2f30d912bcf61ebd6a00 to your computer and use it in GitHub Desktop.
Remove or replace Nth capture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function remove_replace_Nth_capture(src_str,capt,N,repl_str) | |
-- if the last arg is omitted or isn't a string then works for removal | |
-- 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 | |
local N = N and tonumber(N) and math.abs(math.floor(N)) -- validate N | |
if not N then N = 1 end | |
local repl_str = repl_str and type(repl_str) == 'string' and repl_str | |
local cntr = 0 | |
local str_new = '' | |
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 repl_str then | |
if N == cntr then w1, w2 = repl_str..w2, '' end | |
str_new = str_new..w1..w2 | |
elseif N ~= cntr then | |
str_new = str_new..w1..w2 | |
end | |
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