1

给定输入[tag] Content [inner-tag] Inner [/inner-tag][/tag],我将如何验证是否存在[/tag]匹配的关闭[tag]

现在我的规则检查下一个立即标记是否与最后一个开始标记匹配:

tagblock =
  opentag:opentag content:content? closetag:closetag
    { if(opentag.name != closetag.name) {
        throw new this.SyntaxError("No closing tag found for " + opentag.name); 
      } else { 
        return { name:opentag.name, content:content }
      }
    }

这适用于[tag] Content [/tag]但不适用于上面的嵌套输入。

您如何使用 peg.js 处理这样的内部递归?

4

1 回答 1

1

这是我想出的那个。

Content =
  (Element / Text)*

Element =
  startTag:sTag content:Content endTag:eTag {
    if (startTag != endTag) {
      throw new Error(
        "Expected [/" + startTag + "] but [/" + endTag + "] found."
      );
    }

    return {
      name:    startTag,
      content: content
    };
  }

sTag =
  "[" name:TagName "]" { return name; }

eTag =
  "[/" name:TagName "]" { return name; }

TagName = chars:[a-z-]+ { return chars.join(""); }
Text    = chars:[^[]+  { return chars.join(""); }

将其加载到nodejs中后:

var PEG=require('./markup.js'); 
var str = '[tag] Content [inner-tag] Inner [/inner-tag][/tag]';
PEG.parse(str);

结果是:

[ { name: 'tag',
    content: [
        ' Content ',
        { name: 'inner-tag',
          content: [ ' Inner ' ] }
    ]
} ]
于 2014-09-28T21:07:55.967 回答