给定一个字符串,我想用链接的描述替换其中的所有链接.例如,给定
this is a [[http://link][description]]
Run Code Online (Sandbox Code Playgroud)
我想回来
this is a description
Run Code Online (Sandbox Code Playgroud)
我使用re-builder为链接构建了这个正则表达式:
\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]
Run Code Online (Sandbox Code Playgroud)
这是我的功能:
(defun flatten-string-with-links (string)
(replace-regexp-in-string "\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]"
(lambda(s) (nth 2 (split-string s "[\]\[]+"))) string))
Run Code Online (Sandbox Code Playgroud)
它不是替换整个正则表达式序列,而是替换尾随的"]]".这就是它产生的:
this is a [[http://link][descriptiondescription
Run Code Online (Sandbox Code Playgroud)
我不明白出了什么问题.任何帮助将非常感激.
更新:我已经改进了链接的正则表达式.这与问题无关,但如果有人要复制它,他们也可以获得更好的版本.
你的问题是split-string破坏匹配数据,这
replace-regexp-in-string依赖于不变,因为它将使用匹配数据来决定要删除的字符串的哪些部分.这可以说是一个doc bug,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))
Run Code Online (Sandbox Code Playgroud)