I am trying to "extract" my search results into a new buffer, but only the matches - not the whole lines.

For example I am trying to get a list of HTML color codes used in a file. I can identify them (in this case) with a search for "#.*?", which produces:

enter image description here

However, now I want all those matches copied into a new buffer to work on. I just can't seem to figure out how to do this?

  • What are you going to do with them after you edit them? Will you be returning the modified codes to the original file?
    – Tyler
    Jun 28, 2021 at 18:18
  • No - importing them into a reference document for a style guide.
    – MT.
    Jun 28, 2021 at 19:27
  • In other words, I don’t need to “return” them. I’m just trying to get a list of them easily. I can actually do this very easily in Sublime - but I’d like to understand the emacs or evil way to do it (if there is one).
    – MT.
    Jun 28, 2021 at 19:28

1 Answer 1


C-u M-x occur \"\(#[^\"]+\)\" <RETURN> \1

(this strips the quotes)


C-u M-x occur "#.+\" <RETURN>

(this keeps the quotes)

occur finds all lines that match the provided regexp. Calling it with the prefix argument (C-u) returns only the matched text, not the complete lines. Using the capture group (\(...\)) lets you select the group, while ignoring the enclosing quotes. If you don't care about including the quotes, you can drop the capture group.

For example:

(let (
      (base00 "#081724")
      (base01 "#033340")
      (base02 "#1d5483")
      (base03 "#2872b2")
      (base04 "#d3f9ee")
      (base05 "#a6f3dd")
      (base06 "#effffe")
      (base07 "#fffed9")
      (red "#ff694d")
      (orange "#f5b55f")
      (yellow "#fffe4e")
      (magenta "#afc0fd")
      (violet "#96a5d9")
      (blue "#bad6e2")
      (cyan "#d2f1ff")
      (green "#68f6cb")
      (twsblue "#0000ff"))

Calling occur as above produces:

  • 1
    Thanks, this answered my question. I'm only 5 days into emacs, so I had never even heard of the prefix argument - thanks for that. For any that follow, I often want to do this immediately after doing a / search. I wrapped a function to make this work using the last thing you searched for (note, I'm using evil, so you might need to tweak the reference to the search pattern if not): gist.github.com/mtwomey/629bb4b2163450117b7a4c8fdcc8eb4a
    – MT.
    Jun 29, 2021 at 1:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.