我是 PEGjs 的新手,我正在尝试编写一个 PEGjs 语法,将 RegEx 转换(\s*[\(])|(\s*[\)])|(\"[^\(\)]+?\")|([^\(\)\s]+)
为语法。
基本上我想做的是转换测试输入
(App= smtp AND "SPort" != 25) OR (App= pop3 AND "SPort" != 110) OR (App = imap AND "SPort" != 143) AND (App= imap OR "SPort" != 143)
为如下的json格式
{
"eventTypes": [
"All"
],
"condition": {
"operator": "and",
"terms": [
{
"operator": "or",
"terms": [
{
"operator": "or",
"terms": [
{
"operator": "and",
"terms": [
{
"name": "App",
"operator": "equals",
"value": "smtp"
},
{
"name": "Sport",
"operator": "notEquals",
"value": "25"
}
]
},
{
"operator": "and",
"terms": [
{
"name": "App",
"operator": "equals",
"value": "pop3"
},
{
"name": "Sport",
"operator": "notEquals",
"value": "110"
}
]
}
]
},
{
"operator": "and",
"terms": [
{
"name": "App",
"operator": "equals",
"value": "imap"
},
{
"name": "Sport",
"operator": "notEquals",
"value": "143"
}
]
}
]
},
{
"operator": "or",
"terms": [
{
"name": "App",
"operator": "equals",
"value": "imap"
},
{
"name": "Sport",
"operator": "notEquals",
"value": "143"
}
]
}
]
}
}
我已经编写了一些复杂的 javascript 代码来将示例输入转换为 JSON 格式显示,但是代码有点复杂并且不容易长期维护,所以我想尝试一下语法解析器。由于我是语法世界的新手,我寻求一些帮助或指导来实现上述语法,以便我可以根据需要进行增强/编写?
编辑
Javascript解决方案:
var str = '((Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25)) OR (Application = pop3 AND "Server Port" != 110) OR (Application = imap AND "Server Port" != 143) AND (Application = imap OR "Server Port" != 143)';
var final = str.replace(/\((?!\()/g,"['") //replace ( with [' if it's not preceded with (
.replace(/\(/g,"[") //replace ( with [
.replace(/\)/g,"']") //replace ) with ']
.replace(/\sAND\s/g,"','AND','") //replace AND with ','AND','
.replace(/\sOR\s/g,"','OR','") //replace OR with ','OR','
.replace(/'\[/g,"[") //replace '[ with [
.replace(/\]'/g,"]") //replace ]' with ]
.replace(/"/g,"\\\"") //escape double quotes
.replace(/'/g,"\""); //replace ' with "
console.log(JSON.parse("["+final+"]"))