像/\s(foo|bar|baz)\s.*/这样的正则表达式将匹配以下字符串:
football bartender bazooka baz to the end
^^^^^^^^^^^^^^^是否有可能制定语法解析表达式,以类似的方式解析字符串,将字符串分成头和尾?
Result <- Head Tail
football bartender bazooka baz to the end
Head | Tail发布于 2022-03-15 16:36:16
是的,使用PEG是可以实现的。下面是一个使用聚乙二醇的示例
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://stackoverflow.com/questions/71475119
复制相似问题