How to find the nth occurence of a string
Tony Balinski
ajbj at free.fr
Fri Oct 13 16:18:35 CEST 2006
Quoting Eric Bouyoux <eric.bouyoux at insidefr.com>:
> Hi,
>
> Has anybody already written a macro that help to find the nth occurence
> ofa string ?
You can almost do it with a regex: given N as a decimal, searching for
(?:(?n.*?)(?:SearchString)){N}
will select from where you are upto the end of the Nth occurrence of
SearchString.
So a macro could be written looking like this:
=========================================================================
title = "Search for Nth"
re = string_dialog(title "\nEnter RE to find")
if (re == "")
return dialog(title "\nNo RE to find")
n = string_dialog(title "\nFind which occurrence of '" re "'?", \
"From start", "From cursor")
if (!valid_number(n) || n < 1)
return dialog(title "\nNo RE occurrence number to find")
if ($string_dialog_button == 1)
pos = 0
else
pos = $cursor
ok = 1
if (n > 1) # find end of (n-1)th occurrence
{
--n
full_re = "(?:(?n.*?)(?:" re ")){" n "}"
res = search(full_re, pos, "regex")
ok = (res >= 0)
pos = $search_end
}
if (ok) # find final occurrence
{
res = search(re, pos, "regex")
ok = (res >= 0)
}
if (!ok)
return dialog(title "\nThe following RE was not found " \
(n + 1) " times:\n " re)
select(res, $search_end)
set_cursor_pos($search_end)
=========================================================================
More information about the Discuss
mailing list