Perform boolean arithmetic, including regular expression parentheses?

Is there one regular expression that can parse a string (in Python and / or Javascript, doesn't have to be the same expression), which is simple logical arithmetic? For example, I want to parse this line:

a and (b and c) and d or e and (f or g)

Assuming:
* parentheses do not nest
* members a, b, ..., z are not subexpressions

The resulting captures must first be grouped in parentheses, after which I will again deal with the same or simpler regular expression.

I managed to write a naive regular expression for parsing Boolean arithmetic without parentheses.

Any ideas?

+5
source share
3 answers

Usually for this task you, for example, use a recursive descent parser , but you can capture all parts (tokens) using a regular expression

x = 'a and (b and c) and d or e and (f or g)'
import re

matches = re.findall(r'\(.*?\)|\w+', x)
print ','.join(matches)

Operators usually have different priorities . First, brackets will be evaluated, then expressions, andand finally expressions or, with order from left to right in case of equal priority. You say you want to wrap the matches first, but actually what you usually do is use the parts that create the expression tree and recursively evaluate.

+2
source

, , . , ( / , ):

>>> expr = 'a and (b and c) and d or e and (f or g)'
>>> regex = re.compile('\((\w+)\s+(and|or)\s+(\w)\)|(\w+)')
>>> results = regex.findall(expr)
>>> results = [i[:3] if i[0] else i[3] for i in results]
>>> results
['a', 'and', ('b', 'and', 'c'), 'and', 'd', 'or', 'e', 'and', ('f', 'or', 'g')]

3 (--), - ( ).

, . , , , (, AND , AND, ORs).

+1

- pyparsing SimpleBool.py, , :

test = ["p and not q",
        "not not p",
        "not(p and q)",
        "q or not p and r",
        "q or not (p and r)",
        "p or q or r",
        "p or q or r and False",
        ]

(, , .)

:

boolOperand = Word(alphas,max=1) | oneOf("True False")
boolExpr = operatorPrecedence( boolOperand,
    [
    ("not", 1, opAssoc.RIGHT, BoolNot),
    ("and", 2, opAssoc.LEFT,  BoolAnd),
    ("or",  2, opAssoc.LEFT,  BoolOr),
    ])

BoolNot, BoolOr BoolAnd. operatorPrecedence , , , , . operatorPrecedence , boolExpr . BoolXxx. eval, :

p = True
q = False
r = True
for t in test:
    res = boolExpr.parseString(t)[0]
    print t,'\n', res, '=', bool(res),'\n'

pyparsing , , . MIT , .

+1
source

All Articles