How to find the nth occurence of a string
Eric Bouyoux
eric.bouyoux at insidefr.com
Wed Oct 18 11:31:37 CEST 2006
Tony Balinski a écrit :
Quoting Eric Bouyoux [1]<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}
Hi,
Is anybody able to explain me this regexp. I thought I was able to
understand regular expression but it seems I'm not.
Regards.
Eric.
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)
=========================================================================
References
1. mailto:eric.bouyoux at insidefr.com
More information about the Discuss
mailing list