我有一个允许的水果列表,必须确保配置文件包含所有这些水果,并且仅在单独的行中包含这些水果,如下所示。配置文件还有其他配置行。可以说允许的水果是apple,banana,樱桃,那么有效的配置文件将如下所示:
fruit apple
some other config line
############
fruit banana
fruit cherry
other config 1
other config n
关于用Java正则表达式来检查是否列出了所有三个允许的水果并且仅列出了那些水果的任何想法。例如:如果在单独的行中列出了第四个水果,则配置文件无效。
我可以使用两个正则表达式来实现。一个必须包含所有正则表达式,第二个必须包含所有正则表达式以检查它是否不包含任何其他正则表达式:
Positive - contain all
^(?=.*?^fruit banana)(?=.*?^fruit cherry)(?=.*?^fruit apple).*$
Must not contain anything else
^fruit (?!apple|banana|cherry)
任何人都可以提出一个正则表达式吗?谢谢。
这是一个符合您描述的正则表达式:
^((?!\bfruit\b).)* # nothing with "fruit" before
( # then, either:
# 1. fruit apple, followed by things that are not "fruit", followed by fruit banana, non-fruits, and then fruit cherry, or vice versa
\bfruit\b\ apple((?!\bfruit\b).)*(\bfruit\b\ banana((?!\bfruit\b).)*fruit\ cherry|fruit\ cherry((?!\bfruit\b).)*fruit\ banana)
|
# 2. Same with banana at the beginning
fruit\ banana((?!\bfruit\b).)*(fruit\ apple((?!\bfruit\b).)*fruit\ cherry|fruit\ cherry((?!\bfruit\b).)*fruit\ apple)
|
# 3. And with cherry
fruit\ cherry((?!\bfruit\b).)*(fruit\ apple((?!\bfruit\b).)*fruit\ banana|fruit\ banana((?!\bfruit\b).)*fruit\ apple)
)
((?!\bfruit\b).)*$ # no more fruit
由于我不知道Java正则表达式的工作原理,因此我使用Python的详细正则表达式模式进行了此编写,以使它们的编写更为简洁,但这可以在任何功能强大的正则表达式引擎中进行翻译。
加入您的前瞻:
(?ms)^(?!.*?^fruit (?!apple|banana|cherry))(?=.*?^fruit banana)(?=.*?^fruit cherry)(?=.*?^fruit apple).*$
请参见proof,它起作用。
开始时的(?!.*?^fruit (?!apple|banana|cherry))
将确保没有以fruit
开头的行,后跟空格,然后没有apple
,banana
或cherry
。