我正在努力学习peg.js,并希望解析简单的文本“块”,但我很难从语法中得到“可能的无限循环”错误,但是我很难对顺序行进行分组。
目标:
line 1
line 3
line 4
line 6当被解析时会变成:
{
"type": "root",
"children": [
{ type: "para", content: "line 1" },
{ type: "para", content: "line 3\nline 4" },
{ type: "para", content: "line 6" },
]
}换言之:
我可以编写与行和空行相匹配的语法(请参阅http://peg.arcanis.fr/4f4NdP/),但是,为了使多个连续行后面的空行(或EOF)变成段落,我所做的任何事情都会导致递归错误。我觉得这是一个非常简单的n00b的东西,我只是错过了,因为我从来没有使用过聚乙二醇。
我知道我可以在初始化程序块中编写一个全局函数,并跟踪最后一个元素并使其上下文化,但我觉得这并不是真正使用语法的方式。
发布于 2017-06-23 13:50:36
你知道在那些星期里,你挣扎了一天左右,然后终于放弃了,吞下你的骄傲,贴出一个问题,堆积如山.十分钟后就知道答案了?是啊!那是我的一周。我认为写问题的过程会让你以不同的方式思考这个问题,你的突触又开始发火了。
不管怎样,这里有一个解决方案:http://peg.arcanis.fr/4f4NdP/2/
后世语法:
start = head:Para tail:(newline Para)*
{
var t;
t = tail.reduce(function(memo, element) {
return memo.concat(element[1]);
}, []);
return {
type: 'root',
children: [ head ].concat(t),
}
}
Para = text:LineOfText+
{ return { type: 'para', content: text.join('\n') } }
LineOfText = text:$(char+) EOL
{ return text }
char = [^\n\r]
newline = '\n' / '\r' '\n'?
EOL = newline / !.输入:
line 1
line 3
line 4
line 6输出:
{
"type": "root",
"children": [
{
"type": "para",
"content": "line 1"
},
{
"type": "para",
"content": "line 3
line 4"
},
{
"type": "para",
"content": "line 6"
}
]
}https://stackoverflow.com/questions/44722825
复制相似问题