这是我所拥有的:
{a} {b} over {c} {d}
{a} {{b} over {c}} {d}
(我有一些文字,它有这样的表达方式)我想将两者都转换为:
{a} \frac{b}{c} {d}
这是我最好的选择:
(goto-char (point-min))
(while (search-forward-regexp "{+?\\(.+?\\)} +over +{\\(.+?\\)}+?" nil t)
(replace-match (concat "\\\\" "frac{\\1}{\\2}") t nil))
但它不起作用。我得到:
\frac{a} {b}{c} {d}
\frac{a} {{b}{c}} {d}
分别。
问题是——我的正则表达式在左边尽可能多地捕获。虽然我需要它尽可能少地捕获。
编辑:
接受的答案不适用于更复杂的情况(我也需要):
{d^{2} q} over {d t^{2} }
{{d^{2} q} over {d t^{2} }}
(因为嵌套)
这是解析器的工作版本(代码中有趣的部分从 开始while
):
(defun over2frac ()
(interactive)
(let (start end
(case-fold-search nil)
lStart lEnd lStr
rStart rEnd rStr)
(if (use-region-p)
(progn (setq start (region-beginning)) ;; then
(setq end (region-end)))
(progn (setq start (line-beginning-position)) ;; else
(setq end (line-end-position))))
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (search-forward-regexp "{\\(.+\\)}\s*over\s*{\\(.+?\\)}" nil t)
;; r:
(goto-char (match-beginning 2))
(backward-char 1)
(setq rStart (point))
(forward-sexp)
(setq rEnd (point))
(setq rStr (buffer-substring-no-properties rStart rEnd))
;; l:
(goto-char (match-end 1))
(forward-char)
(setq lEnd (point))
(backward-sexp)
(setq lStart (point))
(setq lStr (buffer-substring-no-properties lStart lEnd))
(delete-region lStart rEnd)
(insert "\\" "frac" lStr rStr)
))))
由于它使用forward-sexp
and backward-sexp
-- 并且没有定义syntax-table
-- 它只能在适当的模式下工作(例如rst-mode
and text-mode
-- 但不是emacs-lisp-mode
。对于上面的复杂示例,它给出:
\frac{d^{2} q}{d t^{2} }
{\frac{d^{2} q}{d t^{2} }}
编辑 2:
(defun backslash-func--args-on-both-sides (Find Replace)
(goto-char (point-min))
(while (search-forward-regexp (concat "\\([^{]+\\)}\s*" Find "\s*{\\([^}]+\\)") nil t)
;; r:
(goto-char (match-beginning 2))
(backward-char 1)
(setq rStart (point))
(forward-sexp)
(setq rEnd (point))
(setq rStr (buffer-substring-no-properties rStart rEnd))
;; l:
(goto-char (match-end 1))
(forward-char)
(setq lEnd (point))
(backward-sexp)
(setq lStart (point))
(setq lStr (buffer-substring-no-properties lStart lEnd))
;; s:
(goto-char lStart)
(if (looking-back "{")
(setq lStart (1- (point))))
(goto-char rEnd)
(if (looking-at "}")
(setq rEnd (1+ (point))))
(delete-region lStart rEnd)
(insert "\\" Replace lStr rStr))
(goto-char (point-min))
(while (search-forward-regexp (concat "\\([0-9a-zA-Z_^]+\\)\s*" Find "\s*\\([0-9a-zA-Z_^]+\\)") nil t) (replace-match (concat "\\\\" Replace "{\\1}{\\2}") t nil))
)
这会转换两件事:
{d^{2} q} over {d t^{2} }
{{d^{2} q} over {d t^{2} }}
到
\frac{d^{2} q}{d t^{2} }
我不在let
这里使用,因为所有的变量都已经是本地的了——而 defun 本身在另一个 defun 中。完整代码。