【问题标题】:Emacs Lisp's equivalent of JavaScript's RegExp#execEmacs Lisp 相当于 JavaScript 的 RegExp#exec
【发布时间】:2013-11-23 12:58:43
【问题描述】:

有什么方法可以提取 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 我阅读了此页面,但不知道如何实现这一目标。

【问题讨论】:

    标签: regex emacs elisp


    【解决方案1】:

    要添加到另一个答案,您可能需要将整个 (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")
    

    在所有三个sn-ps中,如果匹配失败,则返回值为nil。

    【讨论】:

    • 感谢您的整个回答。
    【解决方案2】:

    使用string-matchmatch-string

    *** Welcome to IELM ***  Type (describe-mode) for help.
    ELISP> (string-match "^\\(std\\|bcp\\|fyi\\)\\([0-9]+\\)$" "std1")
    0
    ELISP> (match-string 1 "std1")
    "std"
    ELISP> (match-string 2 "std1")
    "1"
    

    请注意,您必须将原始字符串传递给match-string - 它会将偏移量保存在“匹配数据”中,但不保存原始字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2011-01-31
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多