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

Emacs中的正则表达式搜索

  •  1
  • Inaimathi  · 技术社区  · 16 年前

    我正在尝试编写一些Elisp代码来格式化一堆遗留文件。

    其思想是,如果一个文件包含一个类似 "<meta name=\"keywords\" content=\"\\(.*?\\)\" />" ,然后我想插入一个包含现有关键字的节。如果找不到该节,我想在同一节中插入自己的默认关键字。

    (defun get-keywords ()
          (re-search-forward "<meta name=\"keywords\" content=\"\\(.*?\\)\" />")
          (goto-char 0) ;The section I'm inserting will be at the beginning of the file
          (or (march-string 1)
              "Rubber duckies and cute ponies")) ;;or whatever the default keywords are
    

    当函数找不到目标时,它返回 Search failed: "[regex here]" 并阻止其他的评估。有没有办法让它返回默认字符串并忽略错误?

    2 回复  |  直到 16 年前
        1
  •  2
  •   scottfrazer    16 年前

    使用其他选项 re-search-forward 结构更像

    (if (re-search-forward "<meta name=\"keywords\" content=\"\\(.*?\\)\" />" nil t)
        (match-string 1)
      "Rubber duckies and cute ponies")
    
        2
  •  0
  •   offby1    16 年前

    (rx "<meta name=\"keywords\" content=\""
        (group (minimal-match (zero-or-more nonl)))
        "\" />")