代码之家  ›  专栏  ›  技术社区  ›  viam0Zah

Emacs Lisp中的strpos

  •  2
  • viam0Zah  · 技术社区  · 16 年前

    是否有一个本机Emacs Lisp函数的行为类似于 strpos() in PHP search-forward 很好,但是它会修改角色的位置。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Trey Jackson    16 年前

    你可以:

    ;; does not modify match-data
    (string-match-p (regexp-quote "string") (buffer-string))
    

    ;; does modify match-data
    (string-match (regexp-quote "string") (buffer-string))
    

    (defun my-strpos (string)
      "mimic strpos"
      (save-excursion
        (save-match-data
          (goto-char (point-min))               ; or not
          (when (search-forward string nil t)
            (match-beginning 0)))))
    

    这也取决于你找到工作后想做什么。文件 match data 可能有用。如果你想使用 match-data 'save-match-data .

        2
  •  5
  •   Gilles 'SO- stop being evil'    16 年前

    对应于 strpos 在PHP中,在另一个字符串中搜索一个字符串,是 search cl 包裹:

    (require 'cl)
    (search needle haystack :start2 offset)
    

    如果要搜索缓冲区中的字符串,请使用 search-forward . 因为这会更改当前缓冲区和缓冲区内的点,所以需要将函数包装在 save-excursion ;这是一个常见的Emacs Lisp习语。您还应该将函数包装为 save-match-data

    (save-match-data
      (save-excursion
        (set-buffer haystack)
        (goto-char (or offset (point-min)))
        (let ((pos (search-forward needle nil t)))
          ...)))