只是为了好玩,我试图在 PEG.js 中实现你的“语法”
去那里http://pegjs.majda.cz/online并在语法部分(1)上粘贴以下语法。
start
= fruits
fruits
= ft:fruit "@" fts:fruits {fts[ft[0]] = ft[1]; return fts;}
/ ft:fruit {var fruits = {}; fruits[ft[0]] = ft[1]; return fruits;}
fruit
= name:word "-" flavs:flavors {var ft = []; ft.push(name); ft.push(flavs); return ft;}
/ name:word {var ft = []; ft.push(name); ft.push([]); return ft;}
flavors
= flavor:word "#" flavs:flavors {flavs.unshift(flavor); return flavs;}
/ flavor:word { var tab = []; tab.push(flavor); return tab;}
word
= value:[a-zA-Z/]+ {return value.join("");}
然后将句子放入输入部分(2)
Apple-sweet#tangy@Bannana@Orange-citrusy@Pear-crispy#green/yellow
结果来了:
{
"Pear": [
"crispy",
"green/yellow"
],
"Orange": [
"citrusy"
],
"Bannana": [],
"Apple": [
"sweet",
"tangy"
]
}
然后将生成的 javascript 解析器嵌入到一个文件中,您不必为词法/句法分析工作而烦恼。更好的可维护性只能在语义级别恕我直言:)
相当强大的 API,尽管在这种特殊情况下它有点矫枉过正;)