Created
June 13, 2022 09:46
-
-
Save Buy-One/ae0bdcd3c8145824c96713f1ab2d58f1 to your computer and use it in GitHub Desktop.
Remove Nth capture from a string
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_Nth_capture(str,capt,N) -- removes with adjacent punctuation marks | |
-- 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 cntr = 0 | |
local str_new = '' | |
for w1, w2 in 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 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