【问题标题】:elisp regexp search in strings, not bufferselisp 正则表达式搜索字符串,而不是缓冲区
【发布时间】:2011-03-17 18:02:37
【问题描述】:

我一直在 emacs lisp 文档中到处搜索如何将正则表达式搜索到字符串中。我发现的只是如何在缓冲区中执行此操作。

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

【问题讨论】:

    标签: regex string emacs elisp buffer


    【解决方案1】:

    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】:

      您要查找的函数是string-match。如果您需要重复进行匹配,请使用它返回的索引作为下一次调用的可选“开始”参数。该文档位于 ELisp 手册的“正则表达式搜索”一章中。

      【讨论】:

        【解决方案3】:

        要替换字符串中的每个正则表达式匹配项,请查看replace-regexp-in-string

        【讨论】:

          【解决方案4】:

          搜索字符串的开头

          (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))
          

          【讨论】:

            猜你喜欢
            • 2014-08-04
            • 2011-01-01
            • 2015-06-11
            • 2011-07-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多