首页 > 解决方案 > 用于组织模式导出的自定义突出显示的替换正则表达式查询

问题描述

我正在尝试关注这篇博文,并将用户定义的文本标记添加到我的 org 文件中,以便在我的 html 和 latex-pdf 导出中突出显示。

(let ((text (replace-regexp-in-string "[^\\w]\\(@\\)[^\n\t\r]+\\(@\\)[^\\w]" "\\\\hl{"  text nil nil 1 nil)))
        (replace-regexp-in-string "[^\\w]\\(\\\\hl{\\)[^\n\t\r]+\\(@\\)[^\\w]" "}" text nil nil 2 nil)))

(在 org-mode 中)我将要在@符号中突出显示的文本括起来,并为乳胶突出显示进行以下转换。

4 个输入的预期输出:

我的 org-mode 代码块在 4 种情况下测试正则表达式逻辑:

#+begin_src emacs-lisp :tangle yes
    ; 4 regex cases to convert
    (setq mylist '("@highlight me@" "Bill@highlight me@" "@highlight me@Bob" "@highlight me@ and @highlight me@"))

    (defun highlight-attempt (text)
      "replace @text@ with \hl{text}"
        (let ((text (replace-regexp-in-string "[^\\w]\\(@\\)" "}" text nil nil 1 nil)))
          (replace-regexp-in-string "\\(^@\\)[^\\w]" "\\\\hl{" text nil nil 1 nil)))

  (mapcar 'highlight-attempt mylist)
  #+end_src

以上 4 个输入的当前输出:


标签: emacsorg-mode

解决方案


该博客使用了不正确的正则表达式,请参阅elisp regexps。即[^\\w]表示任何不是文字\w-\\w[...]. elisp 中的替代方案是\\W[^[:word:]]。我会使用另一种方法,只是将文本保留在外部“@”之间

(replace-regexp-in-string
 "@\\([^@]+\\)@"
 ;; keep the inner text (match is '\\1' in replacement)
 "\\\\hl{\\1}"
 text)

推荐阅读