I'm new to PEGjs and I'm trying to write a PEGjs grammar convert the RegEx (\s*[\(])|(\s*[\)])|(\"[^\(\)]+?\")|([^\(\)\s]+)
to grammar.
Basically what I'm trying to do is transform the test input
(App= smtp AND "SPort" != 25) OR (App= pop3 AND "SPort" != 110) OR (App = imap AND "SPort" != 143) AND (App= imap OR "SPort" != 143)
to a json format as below
{
"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"
}
]
}
]
}
}
I have written a bit complex javascript code to transform the sample input to the JSON format show about but the code is bit complicated and not easy to maintain in the long term so I thought to give a try a grammar parser. Since I'm new to grammar world, I seek some help or guidance to implement a grammar that does the above so I can enhance/write as needed?
You can see the output of the Regex here
EDIT
Javascript solution:
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+"]"))