Emacs lisp正则表达式从buffer-file-name中提取当前相对路径

时间:2014-03-13 10:04:12

标签: regex emacs elisp

我正在尝试从buffer-file-name变量中提取相对于主目录的当前目录。考虑:

(defun test ()
  (interactive)
  (let ((fn "/home/user/dir1/dir2/file.txt"))
    (when (string-match "^.*?/user/" fn)
      (let ((temp (replace-match "${HOME}/" nil nil fn)))
        (when (string-match "/.*?$" temp)
          (message (replace-match "/" nil nil temp)))))))

在这里,我想获得${HOME}/dir1/dir2/,但我获得了${HOME}/。我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

使用file-relative-name

(concat "$HOME/" (file-relative-name (buffer-file-name) (expand-file-name "~")))

(expand-file-name "~")给出当前用户的主目录。然后file-relative-name将给定的文件名转换为相对于此目录的文件名。

答案 1 :(得分:1)

试试这个:

(let ((str "/home/user/dir1/dir2/file.txt"))
  (when (string-match "^.*?/user/" str)
    (file-name-directory (replace-match "${HOME}/" nil nil str))))