web-dev-qa-db-ja.com

Wordとドットを一致させるC#正規表現

茶色のキツネは怠dogな犬を飛び越えます」は英語のパングラム、アルファベットです。つまり、アルファベットのすべての文字を含むフレーズです。タイプライターのアルファベットをテストするために使用されています。英語のアルファベットのすべての文字を含むアプリケーション。

「アルファベット」を取得する必要があります。正規表現の単語。上記のテキストには3つのインスタンスがあります。 「アルファベット!」を含めないでください。私はちょうど正規表現を試しました

 MatchCollection match = Regex.Matches(entireText, "alphabet."); 

しかし、これは「alphabet!」を含む4つのインスタンスを返します。これを省略して「アルファベット」のみを取得する方法。

31
pili

.は、すべてに一致する正規表現の特殊文字です。エスケープしてみてください:

 MatchCollection match = Regex.Matches(entireText, @"alphabet\.");
42
Håvard

.は、正規表現の特殊文字です。最初にスラッシュでエスケープする必要があります:

Regex.Matches(entireText, "alphabet\\.")

スラッシュは、\は文字列内で別のスラッシュでエスケープする必要があります。

17
Jon

「。」正規表現では特別な意味を持ちます。期間に合わせてエスケープします

MatchCollection match = Regex.Matches(entireText, @"alphabet\.");

編集:

完全なコード、期待される結果を提供:

        string entireText = @"The quick brown fox jumps over the lazy dog is an English-language pangram, alphabet! that is, a phrase that contains all of the letters of the alphabet. It has been used to test typewriters alphabet. and computer keyboards, and in other applications involving all of the letters in the English alphabet.";
        MatchCollection matches = Regex.Matches(entireText, @"alphabet\.");
        foreach (Match match in matches)
        {
            foreach (Group group in match.Groups)
            {
                Console.WriteLine(group);
            }
        }
10
manojlds