Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emacs function re-search-forward interpreting \( \) group characters literally in regexp

I successfully used replace-regexp interactively to replace every instance of quoted text in the buffer shown below with a non-quoted version. The regexp I searched for was

\"\([^\"]*\)\" 

and the NEWTEXT I inserted was \1.

* "PROJECT START"
:PROPERTIES:
:ID: 1
:Unique_ID: 17
:DURATION: "0 days"
:TYPE: "Fixed Work"
:OUTLINE_LEVEL: 1
:END:

Interactively, the aboe text was turned into the text below.

* PROJECT START
:PROPERTIES:
:ID: 1
:Unique_ID: 17
:DURATION: 0 days
:TYPE: Fixed Work
:OUTLINE_LEVEL: 1
:END:

I tried to do this same search and replace programmatically by inserting the following two lines

(while (re-search-forward "\"\([^\"]*\)\"" nil t)
  (replace-match "\1" nil nil ))

at the top of the buffer and executing, but it simply returned nil without finding a single match.

When I omit the

\( \) 

grouping and replace \1 with \&

(while (re-search-forward "\"[^\"]*\"" nil t)
  (replace-match "\&" nil nil ))

I get every quoted string replaced with '&'.

* &
:PROPERTIES:
:ID: 1
:Unique_ID: 17
:DURATION: &
:TYPE: &
:OUTLINE_LEVEL: 1
:END:

Everything I've seen in the documentation for both of these functions indicates that they should recognize these special characters, and the examples of its use in responses to other questions on this forum use these special characters.

Can anyone help me understand why the grouping and \&, \N, \ characters aren't being interpreted correctly?

like image 457
user1593649 Avatar asked Aug 12 '12 16:08

user1593649


1 Answers

You need to escape the "\"s for "(", ")", and "\1". I.e.:

(while (re-search-forward "\"\\([^\"]*\\)\"" nil t)
  (replace-match "\\1" nil nil ))
like image 59
Edward Loper Avatar answered Oct 12 '22 23:10

Edward Loper