gpt4 book ai didi

regex - 用于检测 C++ 模板的 emacs lisp 正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:54 25 4
gpt4 key购买 nike

我试图从 C++ 模板表达式中取出,存储到属性类型中,每个类的单一类型,因此来自类型

`A< B < C < D >> >

我想提取单个类型 A、B、C、D 并将它们放入列表中。`我用 lisp 编写了以下代码:

(if (string-match "\\(\\w+\\)<+\\(\\w+\\)>+$" property-type)
(progn
(setq current-include (match-string 1 property-type) )
(setq current-recursive-property-type (match-string 2 property-type))

但是匹配错误,因为第一个匹配(current-include)是C,余数是D。正则表达式中的错误是什么?

最佳答案

根据定义,正则表达式无法解析任意深层嵌套组,因此一般而言,正则表达式无法真正完成该任务,但是,在这种特殊情况下,您可以假装您正在将字符串拆分为字符 ?\<?\>删除空子字符串时:

(split-string "A< B < C < D > > >" "\\s-*[,<>]+\\s-*" t)

似乎会做你想做的事。

另请注意,如果您要匹配大量文本,并且必须将其设为多行表达式,那么效率很可能会非常低。所以你可以改用这样的东西:

(defun parse-c++-types (type)
(let ((current 0) c types word)
(while (< current (length type))
(setq c (aref type current))
(if (or (char-equal c ?\<) (char-equal c ?\>))
(when word
(setq types (cons (coerce word 'string) types)
word nil))
(unless (memberp c '(?\, ?\ ))
(setq word (cons c word))))
(incf current))
(reverse types)))

(parse-c++-types "A< B < C < D > > >")

关于regex - 用于检测 C++ 模板的 emacs lisp 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12798138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com