我在做一个Peg解析器。在其他结构中,它需要解析标记指令。标签可以包含任何字符。如果您想要标签包括一个卷边大括号},您可以用反斜杠转义它。如果您需要一个文字反斜杠,那也应该转义。我试图实现这个灵感来自于JSON:https://github.com/pegjs/pegjs/blob/master/examples/json.pegjs的Peg语法
有两个问题:
{ some characters but escape with a \\ }\}上中断。示例输入:{ some characters but escape \} with a \\ }相关的语法是:
Tag
= "{" _ tagContent:$(TagChar+) _ "}" {
return { type: "tag", content: tagContent }
}
TagChar
= [^\}\r\n]
/ Escape
sequence:(
"\\" { return {type: "char", char: "\\"}; }
/ "}" { return {type: "char", char: "\x7d"}; }
)
{ return sequence; }
_ "whitespace"
= [ \t\n\r]*
Escape
= "\\"您可以轻松地使用联机PegJS沙箱:https://pegjs.org/online测试语法和测试输入。
我希望有人有办法解决这个问题。
发布于 2021-03-21 20:46:25
供参考,正确的语法如下:
Tag
= "{" _ tagContent:TagChar+ _ "}" {
return { type: "tag", content: tagContent.map(c => c.char || c).join('') }
}
TagChar
= [^}\\\r\n]
/ Escape
sequence:(
"\\" { return {type: "char", char: "\\"}; }
/ "}" { return {type: "char", char: "\x7d"}; }
)
{ return sequence; }
_ "whitespace"
= [ \t\n\r]*
Escape
= "\\"使用下列输入时:
{ some characters but escape \} with a \\ }它将返回:
{
"type": "tag",
"content": "some characters but escape } with a \ "
}https://stackoverflow.com/questions/66730616
复制相似问题