3

我有以下输入字符串:

(
   (
     (App = smtp AND "Server Port" != 25) 
     OR 
     (App = pop3 AND "Server Port" == 20)
   ) 
   AND 
     (App = smtp AND "Server Port" != 35)
 ) 
OR 
(App = pop3 AND "Server Port" != 110) 
AND 
(
   (App = imap AND "Server Port" != 143) 
   OR 
   (App = pop3 AND "Server Port" == 20)
) 
AND (App = imap OR "Server Port" != 143)

想变成:

[
    [
         [
           'App = smtp AND "Server Port" != 25', 
           'OR', 
           'App = pop3 AND "Server Port" == 20'
         ], 
      'AND', 
      'App = smtp AND "Server Port" != 35'
    ], 
   'OR', 
   'App = pop3 AND "Server Port" != 110', 
   'AND', 
   [      
     [
       'App = imap AND "Server Port" != 143', 
       'OR',
       'App = pop3 AND "Server Port" == 20'
     ]
   ], 
   'AND', 
   'App = imap OR "Server Port" != 143'
]

我如何在 pegjs 语法中做到这一点?

我当然可以编写一个 javascript 代码,但我正在寻找 PEGjs 的一些帮助。

4

1 回答 1

1

这应该可以帮助您入门,它大致可以满足您的需求。

start =
    _ ex:expression _
    {
        return ex;
    }

expression =
    op:operand bi:binary?
    {
        return bi ? [op].concat(bi) : op;
    }

operand =
    paren / terminal

paren =
    '(' _ ex:expression _ ')'
    {
        return ex;
    }

binary =
    _ op:operator _ ex:expression
    {
        return [op, ex];
    }

operator =
    'OR' / 'AND'

terminal =
    $((!paren [^)])+)

_ = [\r\n ]*

输出:

[
   [
      [
         "App = smtp AND \"Server Port\" != 25",
         "OR",
         "App = pop3 AND \"Server Port\" == 20"
      ],
      "AND",
      "App = smtp AND \"Server Port\" != 35"
   ],
   "OR",
   [
      "App = pop3 AND \"Server Port\" != 110",
      "AND",
      [
         [
            "App = imap AND \"Server Port\" != 143",
            "OR",
            "App = pop3 AND \"Server Port\" == 20"
         ],
         "AND",
         "App = imap OR \"Server Port\" != 143"
      ]
   ]
]
于 2017-04-27T19:58:12.163 回答