Given a string, I want to replace all links within it with the link’s description. For example, given
this is a [[http://link][description]]
I would like to return
this is a description
I used re-builder to construct this regexp for a link:
\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]
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 regexp sequence, it only replaces the trailing “]]”. This is what it produces:
this is a [[http://link][descriptiondescription
I don’t understand what’s going wrong. Any help would be much appreciated.
UPDATE: I’ve improved the regex for the link. It’s irrelevant to the question but if someone’s gonna copy it they may as well get the better version.
Your problem is that
split-stringis clobbering the match data, whichreplace-regexp-in-stringis relying on being unchanged, since it is going togo use that match data to decide which sections of the string to cut out. This
is arguably a doc bug in that
replace-regexp-in-stringdoes not mention thatyour replacement function must preserve the match data.
You can work around by using
save-match-data, which is a macro provided forexactly this purpose: