[英]Pegjs Expected [0-9.] or end of input but "a" found
I want to handle string starts with number
using pegjs.我想使用 pegjs 处理
string starts with number
。 When I input with 1abcd it throws Expected [0-9.] or end of input but "a" found.
当我用1abcd输入时,它会抛出
Expected [0-9.] or end of input but "a" found.
. . The expected output is
{ item: '1abcd', case: '=' }
.预期输出为
{ item: '1abcd', case: '=' }
。 What changes do I need?我需要什么改变?
var parser = peg.generate(`
start
= number:NUMBER { return { case: "=", item: number } }
/ string:STRING { return { case: "=", item: string.join("") } }
NUMBER
= number:[0-9\.]+ { return parseFloat(number.join("")); }
/ number:[0-9]+ { return parseInt(number.join(""), 10); }
STRING = string:[^*]+ { return string; }
`);
console.log(parser.parse("123"))
console.log(parser.parse("123.45"))
console.log(parser.parse("abcd"))
console.log(parser.parse("abcd-efgh"))
console.log(parser.parse("1abcd"))
The output as follows:输出如下:
{case: "=", item: 123}
{case: "=", item: 123.45}
{case: "=", item: "abcd"}
{case: "=", item: "abcd-efgh"}
Sandbox: https://codesandbox.io/s/javascript-testing-sandbox-forked-5vekz?file=/src/index.js沙盒: https : //codesandbox.io/s/javascript-testing-sandbox-forked-5vekz? file =/ src/ index.js
Since NUMBER
matches the first character, you'll want to use a negative lookahead for STRING
before returning a successful match.由于
NUMBER
匹配第一个字符,因此在返回成功匹配之前,您需要对STRING
使用负前瞻。 That way, if a STRING
character is encountered, the NUMBER
rule will fail and the second alternation of start
will be used.这样,如果遇到
STRING
字符,则NUMBER
规则将失败,将使用start
的第二个交替。
Here's an example, although as @thinkgruen has written, you'll probably want to try to parse floats less loosely as well.这是一个示例,尽管正如@thinkgruen 所写的那样,您可能还想尝试不那么松散地解析浮点数。
start
= number:NUMBER { return { case: "=", item: number } }
/ string:STRING { return { case: "=", item: string.join("") } }
NUMBER
= number:[0-9\.]+ (!STRING) { return parseFloat(number.join("")); }
/ number:[0-9]+ (!STRING) { return parseInt(number.join(""), 10); }
STRING = string:[^*]+ { return string; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.