regex - Emacs Lisp 相当于 JavaScript 的 RegExp#exec

标签 regex emacs elisp

有什么方法可以在 Emacs Lisp 中提取正则表达式的组吗?

例如,如何使用正则表达式从“std1”中获取“std”和“1”

^\(std\|bcp\|fyi\)\([0-9]+\)$

喜欢 JavaScript

/^(std|bcp|fyi)([0-9]+)$/.exec("std1")[1]  //= std
/^(std|bcp|fyi)([0-9]+)$/.exec("std1")[2]  //= 1

http://www.gnu.org/software/emacs/manual/html_node/elisp/Regexp-Functions.html#Regexp-Functions 我阅读了此页面,但无法理解如何实现这一目标。

最佳答案

要添加到其他答案,您可能需要记住整个 (when (string-match ...) (do-something-with (match-string ...)))模式作为成语。示例:

(let ((str "std1")
      (reg (rx bos
               (group (or "std" "bcp" "fyi"))
               (group (+ digit))
               eos)))
  (when (string-match reg str)
    (list :1 (match-string 1 str)
          :2 (match-string 2 str))))

⇒ (:1 "std" :2 "1")

此外,s.el 库中的 s-match 将子匹配项收集到一个列表中:

(require 's)
(let ((str "std1")
      (reg (rx bos
               (group (or "std" "bcp" "fyi"))
               (group (+ digit))
               eos)))
  (s-match reg str))

⇒ ("std1" "std" "1")

然后你可以像这样访问元素:

(require 's)
(require 'dash)

(let ((str "std1")
      (reg (rx bos
               (group (or "std" "bcp" "fyi"))
               (group (+ digit))
               eos)))
  (--when-let (s-match reg str)
    (list :1 (elt it 1)
          :2 (elt it 2))))

⇒ (:1 "std" :2 "1")

在所有三个片段中,如果匹配失败,返回值为 nil。

关于regex - Emacs Lisp 相当于 JavaScript 的 RegExp#exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162573/

相关文章:

emacs - 在 emacs lisp 中启动进程,该进程在 lisp 程序结束后继续

正则表达式只匹配到第一次出现类匹配

java - 修剪字符串以获得java中的第二个单词,第三个单词和第四个单词?

同一窗口中的 Emacs gdb speedbar

windows - Emacs + 史莱姆 + SBCL ( Windows )

git - Emacs:为什么 shell 命令 "git log"有效,但 "git shortlog"无效?

emacs - Emacs 的 GLSL 主要模式?

Oracle SQL 中的正则表达式,正向展望

PHP 正则表达式 preg_match_all div 不相同 id

Emacs:在 TRAMP 模式下禁用 Ido 完成