In emacs-lisp, how to use replace-regexp-in-string correctly?

Given a string, I want to replace all links inside it with a link description. For example, given

this is a [[http://link][description]]

I would like to return

this is a description

I used re-builder to create this regex for reference:

\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]

This is my function:

(defun flatten-string-with-links (string)
    (replace-regexp-in-string "\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]"
                (lambda(s) (nth 2 (split-string s "[\]\[]+"))) string))

Instead of replacing the entire sequence of regular expressions, it replaces only the final "]]". This is what it produces:

this is a [[http://link][descriptiondescription

I do not understand what is going on. Any help would be greatly appreciated.

The UPDATE . I improved the regex for the link. This is not relevant to the question, but if someone copies it, he may also get a better version.

+5
source share
1 answer

, split-string , replace-regexp-in-string , , , . , doc , replace-regexp-in-string , .

save-match-data, , :

(defun flatten-string-with-links (string)
    (replace-regexp-in-string "\\[\\[[a-zA-Z:%@/\.]+\\]\\[[a-zA-Z:%@/\.]+\\]\\]"
                (lambda (s) (save-match-data
                         (nth 2 (split-string s "[\]\[]+")))) string))
+7

All Articles