1

我试图摆脱一个 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))

但是匹配是错误的,因为第一个匹配(当前包含)是 C,其余的是 D。正则表达式中的错误是什么?

4

2 回答 2

1

根据定义,正则表达式无法解析任意深度嵌套组,因此通常使用正则表达式实际上无法完成该任务,但是,在这种特殊情况下,您可以假装将字符串拆分为字符?\<?\>同时删除空子字符串:

(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 > > >")
于 2012-10-09T13:11:08.733 回答
0

假设每个类名前面都有 a 是正确的<吗?如果是这样,您可以轻松匹配(未转义)

(\w+)(?:\s*<\s*(\w+))*

提取任何单个类名。

  • (\w+)是第一堂课
  • (?:是非捕获组
    • \s*<\s*之前和之后的空格<
    • (\w+)
    • )*该组重复零次或多次

是一个使用命名组来展示其工作原理的示例,第二组是多重匹配,最后一个是 D。

于 2012-10-09T10:51:32.893 回答