我得到了一个语法支持:
AND,OR,NOT,(和),“,'
我需要能够解析的一些示例:
考虑到a1,a2等是真实的用户输入,其中可能包括几乎所有类似内容:
我遇到的问题是,其中一个单词没有引号,并以一些保留关键字开头,例如:
在这种情况下,此解析器考虑:
那是我遇到的问题。
我已经尝试了两天的各种解决方案,可以在stackoverflow(和官方文档)上找到:
(以及许多其他方法)试图找到具有这些约束的解决方案:
这是我想出的代码:
content = andOperator
andOperator
= head:orOperator tail:(_ "AND"i _ orOperator)* {
return tail.reduce(function(result, element) {
return {
type: "and",
value: {
left: result,
right: element[3]
}
};
}, head);
}
orOperator
= head:notOperator tail:(_ ("OR"i / _) _ notOperator)* {
return tail.reduce(function(result, element) {
return {
type: "or",
value: {
left: result,
right: element[3]
}
};
}, head);
}
notOperator
= head:parenthesis tail:(_ ("AND"i / "OR" / _) _ "NOT"i _ parenthesis)* {
return tail.reduce(function(result, element) {
var type = (element[1] && element[1].toLowerCase() === "or") ? "or" : "and";
return {
type: type,
value: {
left: result,
right: {
type: "not",
value: element[5]
}
}
};
}, head);
}
parenthesis "Parenthesis"
= _ "(" _ inside:content+ _ ")" _ {
return {
type: "parenthesis",
value: (Array.isArray(inside) && inside.length === 1) ? inside[0] : inside
};
} / text
/*
-----------------------------
TEXT
-----------------------------
*/
text "Text"
= _ inside:(singleQuoteText / doubleQuoteText / noQuoteText)+ _ {
return (Array.isArray(inside) && inside.length === 1) ? inside[0] : inside;
}
singleQuoteText "Single Quote Text"
= "'" text:$([^\']+) "'" {
return {
type: "text",
value: text ? text.trim(): text
};
}
doubleQuoteText "Double Quote Text"
= '"' text:$([^\"]+) '"' {
return {
type: "text",
value: text ? text.trim(): text
};
}
noQuoteText "No Quote Text"
= text:$(!reserved .)+ {
return {
type: "text",
value: text ? text.trim(): text
};
}
reserved "List of keyword this grammar allow"
= ("AND"i / "OR"i / "NOT"i / "(" / ")" / "'" / '"' / " ")
/*
-----------------------------
WHITESPACE PARSING
-----------------------------
*/
__ "Mandatory Whitespace"
= $(whitespace+)
_ "Optional Whitespace"
= __?
whitespace
= [\u0009\u000B\u000C\u0020\u00A0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000] / $('\r\n' / '\n')
问题示例:您好折纸
给出当前的语法:
{
"type": "or",
"value": {
"left": {
"type": "text",
"value": "hello"
},
"right": {
"type": "text",
"value": "igami"
}
}
}
应该给予(它认为折纸是一个完整的世界,而不是+折纸):
{
"type": "or",
"value": {
"left": {
"type": "text",
"value": "hello"
},
"right": {
"type": "text",
"value": "origami"
}
}
}
当前解析器中的折纸被拆分为OR + igami,而它应该考虑整个单词origami ...
答案 0 :(得分:0)
使用谓词,您可以包括一个匹配除关键字之外的所有单词的规则,如下所示:
{
var keywords = ["and", "or"];
}
Expression =
word:$(Word) { return { word: word } } /
keyword:$(Keyword) { return { keyword: keyword } }
// Word will match everything except "and" and "or",
// including words like "origami" and "andromede"
Word = word:$([a-zA-Z]+) &{ return !keywords.includes(word) }
Keyword = [a-zA-Z]+
在以上语法中,Word
将匹配除“或”和“与”之外的所有单词。如果该单词(然后是 entire 单词)是这些关键字之一,则Keyword
规则将匹配。
因此,给定输入and
,您将获得以下输出:
{
keyword: "and"
}
但是给定输入andromede
,您将获得以下输出:
{
word: "andromede"
}