2011-02-04 60 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,這是爲 正是爲此宏解決

相關問題