2016-05-28 7 views
1

2つの特定の単語を含む文章をフィルタリングしたい。私は適切なパターンを探して、私はこれを持っています:正規表現で2つの単語を一致させるための正しいパターン

/^(?=.*\bWord1\b)(?=.*\bWord2\b).*$/ 

しかし、それはネット正規表現で動作しません。 regexクラスのregexで2つの単語を正規表現と照合するための正しいパターンは何ですか?あなたの正規表現に予め

答えて

4

エラー

^(?=.\bWord1\b)(?=.\bWord1\b) 

感謝あなたの正規表現は、非単語(in start of the sentence due to ^)と一致してWord1を見つけることを言います。 Word2と同じです。だから、基本的には、始まりからの手紙の後に両方の言葉が見つかると言っている。

^(non-word) <spaces only for clarity> Word1 
    <------>       <---> 
First . of   and ==>  Find 
lookahead    then ==>  Word1 
matches this 
<--------------> 
As lookaheads are of zero width, the same thing will be applied for Word2. 
So, we are finding Word1 and Word2 both at same position which can't be possible. 
Also your words can be anywhere in sentence and not just after first position. 

修正正規表現

^(?=.*\bword1\b)(?=.*\bword2\b).*$ 

regexstorm demo

正規表現内訳

^ #Starting of string 
(?=.*\bword1\b) #Lookahead to find word1 anywhere in the sentence 
(?=.*\bword2\b) #Lookahead to find word2 anywhere in the sentence 
.* #If both of above is true, then find the whole sentence 
$ #End of string 

C#コード

string input = "word1 abcdkl word2"; 
Regex regex = new Regex(@"^(?=.*\bword1\b)(?=.*\bword2\b).*$"); 

Match match = regex.Match(input); 

if (match.Success) 
{ 
    Console.WriteLine(match.Groups[0].Value); 
} 

Ideone Demo

+0

正規表現filterReg =新しい正規表現( "^(?=。* \ bjackの\ b)は(?=。* \ bjames \ B)。* $" ); doesnt work – Mehdi

+0

@Mehdiはコードを参照してください。正規表現の前に '@'を使用する必要があります。使用しない場合は、\\ b'をダブルエスケープしてください。 – rock321987

+0

ああ、私はverbatinを忘れています。ありがとうございました – Mehdi

関連する問題