Mash
Mash

Reputation: 107

Emacs: How to copy regex matches?

I am simply trying to search/highlight text within a buffer using regex and copy it. I don't want the whole line, just the matches. Any ideas?

I have a large number of lines of text containing tags "[12345][09876]" and I want to regex copy all the tags out.

e.g.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit [12345][09876], 
sed diam nonummy [12345][123456] nibh euismod tincidunt ut laoreet dolore 
magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud [54321][09876] 
exerci tation ullamcorper suscipit lobortis nisl ut aliquip [23451][09656]

Upvotes: 4

Views: 1772

Answers (1)

Oleg Pavliv
Oleg Pavliv

Reputation: 21182

Yes, incremental search does not move the point position, so doing yank won't copy the match.

The easiest solution would probably be the following.

Define a function which copies a search match:

(defun copy-isearch-match ()
    (interactive)
    (copy-region-as-kill isearch-other-end (point)))

And add it to the search mode map

(define-key isearch-mode-map (kbd "M-w") 'copy-isearch-match)

Then doing M-x isearch-forward-regexp you can press M-w to copy the match.

Upvotes: 6

Related Questions