帮你精通Elisp:拆成两把的手术刀 regex.match

一、刻舟求剑也能成功

在 emacs 做文本的查找与替换,就如“刻舟求剑”,不同之处只在于,你能眼睁睁,活生生的看到“刻舟求剑”的策略取得成功。

比如 `string-match` 的例子, 基本语法为:

(string-match REGEXP STRING &optional START)

尝试具体的案例:

ELISP> (string-match "match" "match good match well match perfect")
0 (#o0, #x0, ?C-@)
ELISP> (string-match "match" "match good match well match perfect" 1)
11 (#o13, #xb, ?C-k)
ELISP> (string-match "match" "match good match well match perfect" 12)
22 (#o26, #x16, ?C-v)

而且在不经由中间值的情况下,直接查看匹配结果,

ELISP> (match-end 0)
27 (#o33, #x1b, ?C-[)
ELISP> (match-beginning 0)
22 (#o26, #x16, ?C-v)

查看具体的匹配:

ELISP> (string-match "(bro)(wn)" "The brown fox looks brown.")
4 (#o4, #x4, ?C-d)
ELISP> (match-string 0 "The brown fox looks brown")
"brown"
ELISP> (match-string 1 "The brown fox looks brown")
"bro"
ELISP> (match-string 2 "The brown fox looks brown")
"wn"
ELISP> (match-string 3 "The brown fox looks brown")
nil

我们也可以找到所有的匹配点:

ELISP> (match-data)
(4 9 4 7 7 9)

二、拆成两步的手术刀

再看 regex 的案例,比如将 多行的空行全部替换为单行:

(defun leave-single-blank-line ()
  "replace multiple blank lines with a single one."
  (interactive)
  (goto-char (point-min))
  (while (re-search-forward "(^s-*$)
" nil t)
    (replace-match "
")
    (forward-char 1)))

注意此处 re-search-forward 与 replace-match 的完美搭配。

再看手册中的经典案例:

(with-temp-buffer
  (insert "65 83 68 70")
  (goto-char (point-min))
  (while (re-search-forward "[0-9]+" nil t)
    (replace-match
     ;; "65" => ?A => "A"
     (string (read (match-string 0)))
     'fixedcase
     'literal))
  (buffer-string))
展开阅读全文

页面更新:2024-06-16

标签:手术刀   刻舟求剑   空行   语法   例子   文本   策略   案例   完美   手册   经典   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top