I would like to know a function that searches a pattern located before point.
re-search-backward
is mentioned in the Elisp manual but I do not understand its purpose. Indeed, I do not understand the explanation given in the manual nor some of the cases found.
re-search-backward regexp &optional limit noerror count
This function searches backward in the current buffer for a string of text that is matched by the regular expression regexp, leaving point at the beginning of the first text found.
This function is analogous to
re-search-forward
, but they are not simple mirror images.re-search-forward
finds the match whose beginning is as close as possible to the starting point.re-search-forward
finds the match whose beginning is as close as possible to the starting point. Ifre-search-backward
were a perfect mirror image, it would find the match whose end is as close as possible. However, in fact it finds the match whose beginning is as close as possible (and yet ends before the starting point). The reason for this is that matching a regular expression at a given spot always works from beginning to end, and starts at a specified beginning position.
I did a search but found only unsatisfactory answers.
- emacs greedy search-backward-regexp
- Why is the order of : and - important in a regexp character class
These threads suggest that there is no standard solution. The use of skip-chars-backward
seems to me particularly unsuitable because it is used for the internal workings of Emacs (see syntax.c
).
Suppose the current buffer contains only a string of text composed of alphabetic characters (e.g. abc
), anywhere before the point. In this case, (re-search-backward "[[:alpha:]]+")
moves the point between the last two characters (between b
and c
) when the position is expected to be at the beginning of the text (before a
).
re-search-backwards
doesn't fit your case. I cannot discern what's the problem, if we're talking about greediness backwards, if you want to search forward from the beginning of buffer to point or something else.re-search-backward
and use\=
to match point, orlooking-back
. In the latter case,re-search-backward
should work.