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

elisp regexp在字符串中搜索,而不是在缓冲区中搜索

  •  40
  • Eli  · 技术社区  · 14 年前

    我一直在EmacsLisp文档中到处搜索如何将正则表达式搜索为字符串。我所找到的只是如何在缓冲区中执行这个操作。

    我有什么东西不见了吗?我应该把字符串吐到一个临时缓冲区并在那里搜索它吗?这就是elisp的编码风格,我会习惯的吗?这个问题有标准的解决方案吗?当我能够直接搜索已经存在的变量时,操作缓冲区似乎很笨拙。

    4 回复  |  直到 10 年前
        1
  •  28
  •   user4035    11 年前

    Here is a discussion of string content vs buffer content in the Emacs wiki. 只需将字符串存储为变量即可。

    棘手的事情 about strings 即通常不修改字符串本身(除非对字符串执行数组函数,因为字符串是数组,但通常应避免这样做),但返回修改后的字符串。

    无论如何,这里有一个在elisp中使用字符串的示例。

    这将从字符串结尾处删除空白:

    (setq test-str "abcdefg  ")
    (when (string-match "[ \t]*$" test-str)
        (message (concat "[" (replace-match "" nil nil test-str) "]")))
    
        2
  •  12
  •   Thomas Kappler    14 年前

    你要找的功能是 string-match . 如果需要重复匹配,请使用它返回的索引作为下一个调用的可选“start”参数。文档在elisp手册的“正则表达式搜索”一章中。

        3
  •  3
  •   egdmitry    10 年前

    要替换字符串中的每个regexp匹配项,请查看 replace-regexp-in-string .

        4
  •  1
  •   yPhil Erdogan Oksuz    10 年前

    搜索字符串开头

    (defun string-starts-with-p (string prefix)
        "Return t if STRING starts with PREFIX."
        (and
         (string-match (rx-to-string `(: bos ,prefix) t)
                       string)
         t))
    

    搜索字符串结尾

    (defun string-ends-with-p (string suffix)
      "Return t if STRING ends with SUFFIX."
      (and (string-match (rx-to-string `(: ,suffix eos) t)
                         string)
           t))