我正在尝试为PEG.js编写一个简单的语法,它将匹配下面这样的内容:
some text;
arbitrary other text that can also have µnicode; different expression;
let's escape the \; semicolon, and \not recognized escapes are not a problem;
possibly last expression not ending with semicolon基本上,这些是一些用分号分隔的文本。我的简化语法如下所示:
start
= flow:Flow
Flow
= instructions:Instruction*
Instruction
= Empty / Text
TextCharacter
= "\\;" /
.
Text
= text:TextCharacter+ ';' {return text.join('')}
Empty
= Semicolon
Semicolon "semicolon"
= ';'问题是,如果我在输入中放入分号以外的任何内容,我会得到:
SyntaxError: Expected ";", "\\;" or any character but end of input found.如何解决这个问题?我读到过PEG.js无法匹配输入末尾。
发布于 2012-10-05 20:02:38
您的TextCharacter不应与任何字符( .)匹配。它应该匹配除反斜杠和分号之外的任何字符,或者它应该匹配转义字符:
TextCharacter
= [^\\;]
/ "\\" .第二个问题是,您的语法要求您的输入以分号结尾(但您的输入不以;结尾)。
不如这样吧:
start
= instructions
instructions
= instruction (";" instruction)* ";"?
instruction
= chars:char+ {return chars.join("").trim();}
char
= [^\\;]
/ "\\" c:. {return ""+c;}[
"some text",
[
[
";",
"arbitrary other text that can also have µnicode"
],
[
";",
"different expression"
],
[
";",
"let's escape the ; semicolon, and not recognized escapes are not a problem"
],
[
";",
"possibly last expression not ending with semicolon"
]
]
]请注意,现在尾随的分号是可选的。
https://stackoverflow.com/questions/12743859
复制相似问题