regex 正则表达式模式匹配括号中的短语

5lhxktic  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(130)

我有问题与regex应该接受这样的短语:

"'value'",
"NOT 'value'",
"'value' AND 'value1'",
"'value' OR 'value1'",
"'value' AND NOT 'value1'",
"'value' OR NOT 'value1'",
"'value' AND 'value1' AND 'value2'",
"'value' AND 'value1' OR 'value2'",
"'value' AND 'value1' OR NOT 'value2'",
"('foo' AND 'bar') OR ('baz' AND 'que')",
"('foo' AND 'bar')",
"('foo' OR 'bar')",
"(NOT 'foo' OR 'bar')",
"('NOT 'foo' OR NOT 'bar')",
"('foo' OR NOT 'bar')"

不接受:

"value",
"AND value",
"OR value",
"NOT value",
"'value' 'value2'",
"'value' OR 'value2' 'value3'",
"'value' AND 'value2' 'value3'",
"'value' NOT 'value2' 'value3'",
"(foo AND 'bar') OR ('baz' AND 'que')",
"('foo' 'bar')",
"('foo OR 'bar')"

我有regex:^(?:(?:NOT )?'[^']*')(?:(?: AND | OR )(?:(?:NOT )?'[^']*'))*$但它不适用于括号。你能帮帮我吗?

mi7gmzs6

mi7gmzs61#

您可以从以下语法生成此正则表达式:https://regex101.com/r/bXE6kx/1

%0 = "%j"
%s = '[^']*'
%n = (?:NOT )?%s
%o = (?:%n(?: (?:AND|OR) %n)*)
%b = (?:%o|\(%o\))
%j = %b(?: (?:AND|OR) %b)*

导致正则表达式

^(?:(?:(?:NOT )?'[^']*'(?: (?:AND|OR) (?:NOT )?'[^']*')*)|\((?:(?:NOT )?'[^']*'(?: (?:AND|OR) (?:NOT )?'[^']*')*)\))(?: (?:AND|OR) (?:(?:(?:NOT )?'[^']*'(?: (?:AND|OR) (?:NOT )?'[^']*')*)|\((?:(?:NOT )?'[^']*'(?: (?:AND|OR) (?:NOT )?'[^']*')*)\)))*$

但是说真的,如果它更深了两层,就切换到一个合适的语法解析器,https://ohmjs.org/https://peggyjs.org/或其他东西

相关问题