Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs regexp groups in regex-replace

Tags:

regex

emacs

elisp

I have a bunch of C macros in files, stuff like NEXT( pL ) which is expanded to ( ( pL ) -> next )

I want to remove most of them because they're unnecessary.

What I would like to do, is get the text inside the parentheses in the macro, pL. I want the replacing regexp to use that text for the rewriting. For example, in Perl I could do something like /NEXT\(\s*(.+)\s*) (may be a little incorrect) and then output something like $1->next, which should turn a line

if ( NEXT( pL ) != NULL ) { 

into

if ( pL->next != NULL ) {

In Emacs, I would like to use match groups in an emacs replace-regexp on a file by file basis. I'm not entirely sure how to do this in Emacs.

like image 710
Kizaru Avatar asked Dec 01 '10 21:12

Kizaru


1 Answers

M-x query-replace-regexp NEXT(\([^)]+\)) RET \1->next RET

Which can be done inside a function like so (to apply to an entire buffer)

(defun expand-next ()
  "interactive"
  (goto-char (point-min))
  (while (re-search-forward "\\<NEXT(\\([^\)]+\\))" nil t)
    (replace-match "\\1->next")))

And, to apply this to multiple files, you can mark the files in Dired and type Q to do a query-replace-regexp on all the marked files (use the regexp/replacement in the first line of this answer).

like image 152
Trey Jackson Avatar answered Oct 20 '22 22:10

Trey Jackson