gpt4 book ai didi

解析逻辑表达式的正则表达式

转载 作者:行者123 更新时间:2023-12-04 14:32:40 36 4
gpt4 key购买 nike

我正在尝试使用正则表达式来解析带括号的逻辑表达式
例如:

((weight gt 10) OR (weight lt 100)) AND (length lt 50)
我希望它可以解析为:
Group 1: (weight gt 10) OR (weight lt 100)
Group 2: AND
Group 3: length lt 50
如果这个顺序改变:
(length lt 50) AND ((weight gt 10) OR (weight lt 100))
我希望它可以解析为:
Group 1: length lt 50
Group 2: AND
Group 3: (weight gt 10) OR (weight lt 100)
我试过的成本最高的是这个表达式:
(\((?>[^()]+|(?1))*\))
问题在于它仅部分起作用:
((weight gt 10) OR (weight lt 100)) AND (length lt 50)

Group 1: ((weight gt 10) OR (weight lt 100))
Group 2: (length lt 50)

(length lt 50) AND ((weight gt 10) OR (weight lt 100))

Group 1: (length lt 50)
Group 2: ((weight gt 10) OR (weight lt 100))
逻辑运算符不是作为一个组选择的。
我该如何解决这个问题以捕获逻辑运算符 AND?

最佳答案

使用您显示的示例,请尝试以下正则表达式,用 Python3.8 测试和编写

^(?:\((\(weight.*?\))|\((length[^)]*))\)\s+(AND)\s+(?:\((\(weight.*?\).*?\))|\((length[^)]*)\))$
或通用解决方案:
^(?:\((\(.*?\))|\((\w+[^)]*))\)\s+(\S+)\s+(?:\((\(\w+.*?\).*?\))|\((\w+[^)]*)\))$
这是python3的完整代码:以下结果与示例特定的正则表达式有关,只是将正则表达式更改为通用的(如上所示),它也适用于通用值。
import re
##Scenario 1st here...
var="""((weight gt 10) OR (weight lt 100)) AND (length lt 50)"""
li = re.findall(r'^(?:\((\(weight.*?\))|\((length[^)]*))\)\s+(AND)\s+(?:\((\(weight.*?\).*?\))|\((length[^)]*)\))',var)
[('(weight gt 10) OR (weight lt 100)', '', 'AND', '', 'length lt 50')]

##Scenario 2nd here.
var="""(length lt 50) AND ((weight gt 10) OR (weight lt 100))
li = re.findall(r'^(?:\((\(weight.*?\))|\((length[^)]*))\)\s+(AND)\s+(?:\((\(weight.*?\).*?\))|\((length[^)]*)\))',var)
[('', 'length lt 50', 'AND', '(weight gt 10) OR (weight lt 100)', '')]

##Remove null elements in 1st scenario's find command here.
[string for string in li[0] if string != ""]
['(weight gt 10) OR (weight lt 100)', 'AND', 'length lt 50']

##Remove null elements came in 2nd scenario's find command here.
[string for string in li[0] if string != ""]
['length lt 50', 'AND', '(weight gt 10) OR (weight lt 100)']
说明:为上述正则表达式添加详细说明。
^                                          ##Checking from starting of value.
(?: ##Creating a non-capturing group here.
\( ##Matching literal \ here.
(\(weight.*?\))|\((length[^)]*))\ ##Creating 1st capturing group to match weight till ) OR length before ) as per need.
) ##Closing 1st non-capturing group here.
\s+ ##Matching 1 or more occurrences of spaces here.
(AND) ##Matching AND and keeping it in 2nd capturing group here.
\s+ ##Matching 1 or more occurrences of spaces here.
(?: ##Creating 2nd capturing group here.
\( ##Matching literal \ here.
(\(weight.*?\).*?\))|\((length[^)]*)\) ##Creating 3rd capturing group here which is matching either weight till ) 2nd occurrence OR length just before ) as per need.
)$ ##Closing 2nd non-capturing group at end of value here.

关于解析逻辑表达式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67339826/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com