正則運算式 like/\s(foo|bar|baz)\s.*/將匹配以下字串:
football bartender bazooka baz to the end
^^^^^^^^^^^^^^^
是否可以制定一個決議運算式語法規則,以類似的方式決議字串,將其拆分為頭部和尾部?
Result <- Head Tail
football bartender bazooka baz to the end
Head | Tail
uj5u.com熱心網友回復:
是的,使用 PEG 可以實作。這是使用pegjs的示例:
start = f:words space r:tail
{
return [f, r];
}
tail = f:"baz" space r:words
{
return r;
}
words = f:word r:(space word)*
{
return [f].concat(r).flat().filter(n => n);
}
word = !tail w:$([A-Za-z] )
{
return w;
}
space = " "
{
return;
}
輸出:
[
[
"football",
"bartender",
"bazooka"
],
[
"to",
"the",
"end"
]
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445153.html
