【问题标题】:The lisp that convert string and grep in emacs?在 emacs 中转换字符串和 grep 的 lisp?
【发布时间】:2015-02-11 20:59:07
【问题描述】:

我的文件格式为

abc|<hoge>
a|<foo> b|<foo> c|<foo>
family|<bar> guy|<bar>
a|<foo> comedy|<bar> show|<foo>
action|<hoge>

并希望在 emacs 上按原始搜索字符串(如“喜剧表演”而不是 a|&lt;foo&gt; comedy|&lt;bar&gt; show|&lt;foo&gt;)。

我相信在 lisp 上使用 grep 将是最简单的答案,但我还没有弄清楚如何。有人能启发我吗?

【问题讨论】:

  • "a comedy show"不是将匹配a|&lt;foo&gt; comedy|&lt;bar&gt; show|&lt;foo&gt; 的正则表达式 实用程序grep 包含一个可选参数E,它代表扩展正则表达式。您的问题有点不清楚,但似乎是在询问如何使用 grep 通常使用正则表达式进行搜索,以及如何使用 Emacs 为外部实用程序 grep 提供的前端执行相同的搜索。您可能希望进一步澄清这个问题,甚至包括一个 grep 标记,因为您可能会询问如何使用该实用程序执行特定搜索。
  • user2283547:您想在 Emacs 中进行交互式搜索吗?还是您想查看所有匹配结果的列表?

标签: emacs elisp find-grep


【解决方案1】:

好吧,grep 是一个单独的程序(您也可以使用它)。在 Emacs 中,您将使用函数 search-forward-regexp,您可以使用 M-x 运行它(按住 Meta,通常是 Alt 键,然后按 x)然后键入 search-forward-regexp 并按 @987654328 @。

然后您需要输入正则表达式进行搜索。简而言之,您似乎想忽略 |&lt; something &gt;,在 Emacs 的各种正则表达式中是:

 |<[a-z]+> 

所以你可以搜索例如

 a|<[a-z]+> comedy|<[a-z]+> show|<[a-z]+>

您可以创建一个 Lisp 函数来以这种方式转换字符串,方法是将其拆分为空格并添加正则表达式序列:

(defun find-string-in-funny-file (s)                        ; Define a function
  "Find a string in the file with the |<foo> things in it." ; Document its purpose
  (interactive "sString to find: ")                         ; Accept input if invoked interactively with M-x
  (push-mark)                                               ; Save the current location, so `pop-global-mark' can return here
                                                            ; (usually C-u C-SPC)
  (goto-char 0)                                             ; Start at the top of the file
  (let ((re (apply #'concat                                 ; join into one string…
                   (cl-loop 
                    for word in (split-string s " ")        ; for each word in `s'
                    collect (regexp-quote word)             ; collect that word, plus
                    collect "|<[a-z]+> "))))                ; also the regex bits to skip
    (search-forward-regexp                                  ; search for the next occurrence
     (substring re 0 (- (length re) 2)))))                  ; after removing the final space from `re'

您可以在(在线)Emacs Lisp 手册中了解这些功能各自的作用;例如,从菜单“Help→Describe→Function”中选择或按C-h f(Control+h,然后f)并键入interactive(RET)以获得该特殊形式的手册文档。

如果将上面的(defun)粘贴到*scratch*缓冲区中,并将光标定位在最后的)之后,您可以按C-j对其进行评估,该功能将一直存在,直到你关闭 Emacs。

如果你把它保存在一个名为 something .el 的文件中,你可以在以后使用M-x load-file 再次加载它。

如果您随后加载“有趣”文件并输入 M-x find-string-in-funny-file,它将在您的文件中搜索您的字符串,并将光标留在字符串上。如果未找到,您将看到相关消息。

BUGS:功能不够壮观

【讨论】:

  • 您可以使用regexp-quote 处理单词,以防止意外使用正则表达式特殊字符。
  • 谢谢,我知道它存在。我会修补上面的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多