正则表达式否定先行

 收藏

我正在尝试创建一个正则表达式来检查类似于以下内容的句子:

Some text {word1} some more text {word2} maybe some more text

The string starts with some text then followed by {word1} (including the curly braces), followed with more text, followed by {word2} (including the curly braces), and optionally some final text. The sentence must contain both {word1} and {word2}, it must have {word1} come before {word2}, and both {word1} and {word2} can only appear once in the sentence each.

我为此创建正则表达式遇到很多麻烦,这主要是因为负面的前瞻性。我想看看这里的人是否真的对正则表达式非常满意,并且能够创建一个正则表达式来检查这一点。以下还有一些不应通过的文本示例。

Some text (no word1 or word2)
Some text {word1} some more text (no word2)
Some text {word2} some more text (no word1)
Some text {word1} some more text {word1} some more text {word2} maybe some more text (word1 appears multiple times)
Some text {word2} some more text {word1} maybe some more text (word2 precedes word1)
{word1} some text {word2} maybe some more text (no text preceding word1)
Some text {word1} {word2} maybe some more text (no text between word1 and word2)

任何帮助都将不胜感激。

回复