How to make backward regexp search greedy in emacs?
For example, I have abc 163439 abc
in my buffer, and I run M-x search-backward-regexp with the following regexp: 163439\|3
. This regexp will allways find '3' in the buffer, but newer the whole long number. Because, when it starts search, it will meet '3' firstly. In a second try, it will start from the position of '3', which is inside the number, and it will omit it.
How can I find the longest and closest match?
So I mean, when it meet '3', I want it to check if the matched part isn't the part of a bigger match.
I don't think you can do what you want.
Emacs search-backward-regexp searches for the closest instance that matches the regular exprssion. This is not about greediness (greediness in regular expressions is about matching as many characters as possible when there is a kleene star operator -- or its syntactic variants ? or +).
In your example, emacs properly finds the first instance that matches your regular expression.
--dmg
When asked some years ago, answer was: it's not implemented.
Maybe try this:
(defun ar-greedy-search-backward-regexp (regexp)
"Match backward the whole expression as search-forward would do. "
(interactive (list (read-from-minibuffer "Regexp: " (car kill-ring))))
(let (last)
(when (re-search-backward regexp nil t 1)
(push-mark)
(while (looking-at regexp)
(setq last (match-end 0))
(forward-char -1))
(forward-char 1)
(push-mark)
(goto-char last)
(exchange-point-and-mark))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With