Emacs greedy search-backward-regexp

How to make reverse regex search greedy in emacs?

For example, I have abc 163439 abc in my buffer, and I run Mx search-backward-regexp with the following regexp: 163439\|3 . This regular expression will always find “3” in the buffer, but newest is a long number. Because when he starts the search, he will first meet a "3". In the second attempt, it will start from position “3”, which is inside the number, and it will lower it.

How to find the longest and closest match?

So, I mean, when he meets "3", I want him to check if the matching part of the majority matches.

+4
source share
3 answers

I don’t think you can do what you want.

Emacs search-backward-regexp searches for the closest instance that matches regular exprssion. This is not about greed (greed in regular expressions is to match as many characters as possible when there is a wedge star operator - or its syntactic variants? Or +).

In your example, emacs correctly finds the first instance that matches your regular expression.

- DMG

+1
source

When asked a few years ago, the answer was: it is not implemented.

Perhaps try the following:

 (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)))) 
+1
source

As dmg said, to some extent you can’t do it: the Emacs regexp engine only matches fast forward, so the “back” part only applies to search, not to match. It’s usually best to change your regular expression so you don’t rely on greed. For instance. use \<\(?:163439\|3\) .

+1
source

All Articles