Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I regexp replace a string in an elisp function?

Tags:

regex

emacs

elisp

I'm writing myself a little helper function and one of the things I would like to do in it is to do a replace based on regex. replace-regexp-in-string looked like a good candidate. I'm unable, however, to get it to replace with capture. Here are all the things I have tried based on the emacs wiki:

(replace-regexp-in-string "a(b)c" "d\0f" "abc")
(replace-regexp-in-string "a(b)c" "d \0 f" "abc")
(replace-regexp-in-string "a(b)c" "d\\0f" "abc")
(replace-regexp-in-string "a(b)c" "d \\0 f" "abc")
(replace-regexp-in-string "a(b)c" "d\1f" "abc")
(replace-regexp-in-string "a(b)c" "d \1 f" "abc")
(replace-regexp-in-string "a(b)c" "d\\1f" "abc")
(replace-regexp-in-string "a(b)c" "d \\1 f" "abc")

All of the above seem to evaluate to "abc" which puzzles me greatly. For d\0f, I would expect the result to be "dbf". I'm starting to suspect that this function doesn't do captures.

What is the correct way to do this? Alternatively, what's the way to do this in general? A lot of the functions that deal with replacing regexp only deal with whole buffers while I need to transform some text it place.

like image 813
Mateusz Kowalczyk Avatar asked Oct 15 '25 22:10

Mateusz Kowalczyk


1 Answers

if you'll look into description of this function (C-h f replace-regexp-in-string), you'll notice that captures are specified as \\(regex\\), and refered as \\1, etc. See description of Emacs's regular expressions - they are slightly different from Perl & POSIX regexes.

You can also look onto another functions that works with buffers, for example, as in my config.

like image 109
Alex Ott Avatar answered Oct 17 '25 14:10

Alex Ott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!