Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emacs greedy search-backward-regexp

Tags:

regex

emacs

elisp

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.

like image 970
Necto Avatar asked Apr 30 '13 11:04

Necto


2 Answers

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

like image 131
dmg Avatar answered Oct 17 '22 19:10

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))))
like image 2
Andreas Röhler Avatar answered Oct 17 '22 19:10

Andreas Röhler