2011-02-04 69 views
5

给定一个字符串,我想用链接的描述替换它中的所有链接。例如,给定在emacs-lisp中,我该如何正确使用replace-regexp-in-string?

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

我想回

this is a description 

我用重新生成器来构建这个正则表达式中的链接:

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

这是我的函数:

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

代替第整个正则表达式序列,它只替换尾部的“]]”。这是它生产的:

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

我不明白发生了什么问题。任何帮助将非常感激。

UPDATE:我改进了链接的正则表达式。这与问题无关,但如果有人要复制它,他们可能会得到更好的版本。

回答

7

您的问题是split-string被重挫的比赛数据, replace-regexp-in-string是依托是其不变的,因为它要 去使用匹配的数据,以决定该字符串的部分削减其指出。这 可以说是一个文档错误,replace-regexp-in-string没有提到 您的替代功能必须保留匹配数据。

(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)) 

您可以通过使用save-match-data,这是为 正是为此宏解决

相关问题