5

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?

ekad
  • 14,436
  • 26
  • 44
  • 46
user1593649
  • 115
  • 4

1 Answers1

7

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

(while (re-search-forward "\"\\([^\"]*\\)\"" nil t)
  (replace-match "\\1" nil nil ))
Edward Loper
  • 15,374
  • 7
  • 43
  • 52
  • 2
    If it wasn't clear, this is because ``\`` is special to strings (as well as to regexps). So when you provide a regexp in string format, any backslashes need to be escaped, otherwise the result of the string evaluation would not be the regexp you intended. – phils Aug 13 '12 at 04:02
  • @user1593649: Don't forget that you can accept the answer by clicking the hollow tickmark next to it. – Jack Kelly Aug 13 '12 at 06:47
  • Any idea on how to make it work only inside the selection? – Atreyagaurav Nov 17 '20 at 13:03