I've got a file that looks roughly like this:


assuming my point is at the beginning of the file, how can I find the first pair of lines that match up to the first comma on each line.


Press C-uC-s to begin a regexp search

Search for ^\(.*?,\).*^J\1

Note that to insert the ^J you wont actually type ^J. ^J is the representation of a newline character, you insert this hard new line by typing C-qC-j

So you are searching for: anything not a comma, followed by a comma, followed by anything to the end of the line, followed by a new line, followed by the first matched thing.

You could turn it into a command like so:

(defun find-next-matching-prefix-lines ()
  "Move forward to the next pair of lines that match up to the first comma on each line."
  (if (re-search-forward "^\\(.*?,\\).*\n\\1" (point-max) t 1)
      (goto-char (line-beginning-position))
    (message "no more matches found!")))
|improve this answer|||||
  • His question sounds unclear to me. Does he need to search for prefix\.\w+,? – Kaushal Modi Jan 29 '15 at 18:29
  • I think the word prefix in the text is just an example, not a hard requirment, I think he does actually want "the first pair of lines that match up to the first comma on each line." as he stated. – Jordon Biondo Jan 29 '15 at 18:33
  • that's correct, I'm not looking for a match on the literal "prefix.", the prefix is arbitrary. – gregghz Jan 29 '15 at 18:35
  • Ah alright. You can also use the non-greedy operator ? here.. works the same way: ^\(.*?,\).*^J\1 – Kaushal Modi Jan 29 '15 at 18:41
  • 1
    Be careful, [^,] also matches a newline. – politza Jan 29 '15 at 18:45

You can type:

M-x isearch-forward-regexp RET ^\\(.\*\\),.\* C-q C-j \1,

The cryptic characters in the middle form a regular expression (or regexp), it is a pattern language that you use to describe what you would like to match. The C-q C-j part inserts a newline character.

Effectively, the regexp specifies:

  • ^ It should start at the beginning of a line.
  • \\(.*\\) It should match anything, and capture the matched string in a group (group 1)
  • , Match an explicit comma
  • C-q C-j This inserts a newline character in the regexp that matches the end of a line
  • \1 This should match the same as group 1 matched.
  • , Another explicit comma.
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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