regex 正则表达式模式与值运算符AND OR NOT匹配-搜索引擎

2fjabf4q  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(95)

我试图写regex到我的自定义搜索引擎我的输入文本:

val examples = listOf(
    "'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'",
    "'value' AND NOT 'value1' OR NOT 'value2'",
    "'value' OR 'value1' OR 'value2'",
    "'value' OR 'value1' AND 'value2'",
    "'value' OR 'value1' AND NOT 'value2'",
    "'value' OR NOT 'value1' OR NOT 'value2'",
)
val examplesNotMatched = listOf(
    "value",
    "AND value",
    "OR value",
    "NOT value",
    "'value' 'value2'",
    "'value' OR 'value2' 'value3'",
    "'value' AND 'value2' 'value3'",
    "'value' NOT 'value2' 'value3'",
    "'AND'",
    "'OR'",
    "'NOT'",
    "'testANDtest2'",
    "'testORtest2'",
    "'testNOTtest2'",
    "'ANDtesttest2'",
    "'ORtesttest2'",
    "'NOTtesttest2'",
    "'testtest2OR'",
    "'testtest2AND'",
    "'testtest2NOT'"
)

模式应该符合所有这些情况。我试过这样的东西:

val pattern = Pattern.compile("('(?:[^']*'\\s*(?:AND|OR|NOT)\\s*)*[^']*')\\s*")

但它不起作用。
有人能帮我一下吗?

ha5z0ras

ha5z0ras1#

https://regex101.com/r/d1RUHE/1

^(?:(?:NOT )?'(?![^'\n]*(?:AND|OR|NOT))[^'\n]*')(?:(?: AND | OR )(?:(?:NOT )?'(?![^'\n]*(?:AND|OR|NOT))[^'\n]*'))*$
%0 = ^%p(?:%m%p)*$
%m = (?: AND | OR )
%p = (?:(?:NOT )?%s)
%s = '(?![^'\n]*(?:AND|OR|NOT))[^'\n]*'

(uses https://tsplay.dev/dimava-regex101-markup-2生成结果regex)

相关问题