用正则表达式解析包含括号的布尔算术? [英] Parse boolean arithmetic including parentheses with regex?

查看:56
本文介绍了用正则表达式解析包含括号的布尔算术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个正则表达式可以解析表示简单布尔算术的字符串(在 Python 和/或 Javascript 中,不需要是相同的表达式)?例如我想解析这个字符串:

Is there a single regular expression that can parse a string (in Python and/or Javascript, does not need to be the same expression) that represents simple boolean arithmetic? For example I want to parse this string:

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

假设:
* 括号不嵌套
* 项 a, b, ..., z 不是子表达式

Assuming that:
* parentheses do not nest
* the terms a, b, ..., z are not sub-expressions

生成的捕获应首先按括号分组,然后我使用相同或更简单的正则表达式再次解析.

The resulting captures should be grouped by parentheses first, which I then parse again with the same or a simpler regex.

我已经成功地编写了一个简单的正则表达式来解析没有括号的布尔运算.

I've had success writing a naive regex for parsing boolean arithmetic without parentheses.

有什么想法吗?

推荐答案

通常您会使用例如 递归下降解析器用于此任务,但您可以使用正则表达式获取所有部分(令牌):

Normally you would use for example a recursive descent parser for this task, but you can grab all the parts (tokens) with a regex:

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)

运算符通常具有不同的优先级.括号将首先被评估,然后是 and 表达式,最后是 or 表达式,在相同优先级的情况下从左到右的顺序.你说你想首先返回括号匹配,但实际上你通常会使用这些部分构建一个表达式树并递归计算.

The operators usually have different precedence. Parentheses would be evaluated first, then and expressions, and finally or expressions, with left-to-right order in case of equal precedence. You say you want to return the parentheses matches first, but actually what you would normally do is to use the parts build an expression tree and evalulate that recursively.

这篇关于用正则表达式解析包含括号的布尔算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆