8

正規表現に問題があります。リンゴ、オレンジ、ジュースなど、指定された一連の単語を除いて正規表現を作成する必要があります。これらの単語を指定すると、上記の単語以外のすべてに一致します。

applejuice (match)
yummyjuice (match)
yummy-apple-juice (match)
orangeapplejuice (match)
orange-apple-juice (match)
apple-orange-aple (match)
juice-juice-juice (match)
orange-juice (match)

apple (should not match)
orange (should not match)
juice (should not match)
4

6 に答える 6

10

本当に単一の正規表現でこれを行いたい場合は、ルックアラウンドが役立つことがあります (特に、この例では否定先読み)。Ruby 用に記述された正規表現 (一部の実装では、ルックアラウンドの構文が異なります):

rx = /^(?!apple$|orange$|juice$)/
于 2009-12-01T13:23:12.700 に答える
3

apple-juiceパラメータに従って一致する必要があることに気付きましたが、どうapple juiceですか? 検証している場合apple juiceでも、失敗したいと思っていると思います。

それでは、「境界」としてカウントされる一連の文字を作成しましょう。

/[^-a-z0-9A-Z_]/        // Will match any character that is <NOT> - _ or 
                        // between a-z 0-9 A-Z 

/(?:^|[^-a-z0-9A-Z_])/  // Matches the beginning of the string, or one of those 
                        // non-word characters.

/(?:[^-a-z0-9A-Z_]|$)/  // Matches a non-word or the end of string

/(?:^|[^-a-z0-9A-Z_])(apple|orange|juice)(?:[^-a-z0-9A-Z_]|$)/ 
   // This should >match< apple/orange/juice ONLY when not preceded/followed by another
   // 'non-word' character just negate the result of the test to obtain your desired
   // result.

ほとんどの正規表現フレーバー\bでは、「単語境界」としてカウントされますが、「単語文字」の標準リストには含まれない-ため、カスタムのものを作成する必要があります。/\b(apple|orange|juice)\b/あなたもキャッチしようとしていなければ、それは一致する可能性が-あります...

「単一単語」テストのみをテストしている場合は、はるかに単純なテストを使用できます。

/^(apple|orange|juice)$/ // and take the negation of this...
于 2009-12-01T13:33:21.937 に答える
0

これはいくつかの方法を取得します:

((?:apple|orange|juice)\S)|(\S(?:apple|orange|juice))|(\S(?:apple|orange|juice)\S)
于 2009-12-01T14:37:02.587 に答える
0
\A(?!apple\Z|juice\Z|orange\Z).*\Z

禁止された単語の 1 つだけで構成されていない限り、文字列全体に一致します。

または、Ruby を使用していない場合、または文字列に改行が含まれていないことが確実である場合、または行頭/行末が一致しないオプションを設定して^いる$場合

^(?!apple$|juice$|orange$).*$

も機能します。

于 2009-12-01T15:30:37.810 に答える
-1

(PHP)のようなもの

$input = "The orange apple gave juice";
if(preg_match("your regex for validating") && !preg_match("/apple|orange|juice/", $input))
{
  // it's ok;
}
else
{
  //throw validation error
}
于 2009-12-01T13:10:53.183 に答える