用peg.js返回引用

时间:2014-09-28 09:03:55

标签: javascript peg

根据输入[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处理这样的内部递归?

1 个答案:

答案 0 :(得分: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 ' ] }
    ]
} ]