2009-12-01 23 views
5

正規表現に問題があります。 私はregexを、指定された単語のセットを除いて作る必要があります。例えば、apple、orange、juiceです。 これらの単語を指定すると、上記の単語以外はすべて一致します。正規表現以外の正規表現

apple (should not match) 
applejuice (match) 
yummyjuice (match) 
yummy-apple-juice (match) 
orangeapplejuice (match) 
orange (should not match) 
juice (should not match) 
orange-apple-juice (match) 
apple-orange-aple (match) 
juice-juice-juice (match) 
orange-juice (match) 
+0

あなたはどの言語で作業していますか?また、 "オレンジジュース"と一致するか、失敗する必要がありますか? – gnarf

答えて

-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 
} 
+0

それは 'applejuice'にマッチするので、検証エラーが発生します。 – gnarf

7

あなたが本当に単一の正規表現でこれを行うにしたい場合は、前後参照役立つ(この例では、特に否定先読み)を見つけるかもしれません。ルビー(いくつかの実装は、前後参照のために異なる構文を持っている)のために書かれた正規表現:あなたは単語の文字としてハイフンを扱いたいよう

rx = /^(?!apple$|orange$|juice$)/ 
3

私は、apple-juiceがあなたのパラメータに従って一致するはずですが、apple juiceはどうですか?私はあなたがまだapple juiceを検証しているなら、あなたはまだそれが失敗したいと思っています。 「単語の境界」ではなく「単語文字」の標準リストとして\bカウントdoesnのほとんどの正規表現の風味で

/[^-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. 

」: -

だから「境界」としてカウント文字のセットを構築することができますtには-が含まれていますので、カスタムを作成する必要があります。あなたにも-をキャッチしようとしていなかった場合にのみ、「一単語」テストをテストしている場合、それはあなたがはるかに簡単に行くことができます

... /\b(apple|orange|juice)\b/と一致する可能性:

/^(apple|orange|juice)$/ // and take the negation of this... 
0

これが取得しますそこに道の一部:それだけで禁じられた言葉の一つで構成されていない限り、

((?:apple|orange|juice)\S)|(\S(?:apple|orange|juice))|(\S(?:apple|orange|juice)\S) 
0
\A(?!apple\Z|juice\Z|orange\Z).*\Z 

は、文字列全体にマッチします。

また、^$は、ラインの始まり/端に一致していないことを、あなたは、Rubyを使用していないか、あなたの文字列が何の改行が含まれていないことを確認しているか、オプションを設定している場合

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

も動作します。