文字列を検索する方法

2 つの主な戦略を使用して、文字列のテキストを検索することができます。 String クラスのメソッドは特定のテキストを検索します。 正規表現はテキストのパターンを検索します。

注意

この記事の C# 例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。 [実行] ボタンを選択すると、対話型ウィンドウで例が実行されます。 コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。

string 型は、System.String クラスのエイリアスであり、文字列の内容を検索するための多数の便利なメソッドを提供します。 その中に ContainsStartsWithEndsWithIndexOfLastIndexOf が含まれています。 System.Text.RegularExpressions.Regex クラスでは、テキストのパターンを検索するための豊富なボキャブラリが提供されます。 この記事では、これらの手法と、ニーズに最適なメソッドを選択する方法について説明します。

文字列にテキストが含まれていますか?

String.ContainsString.StartsWithString.EndsWith メソッドでは、特定のテキストの文字列を検索します。 次の例は、これらの各メソッドと、大文字と小文字を区別しない検索を使用するバリエーションを示しています。

string factMessage = "Extension methods have all the capabilities of regular static methods.";

// Write the string and include the quotation marks.
Console.WriteLine($"\"{factMessage}\"");

// Simple comparisons are always case sensitive!
bool containsSearchResult = factMessage.Contains("extension");
Console.WriteLine($"Contains \"extension\"? {containsSearchResult}");

// For user input and strings that will be displayed to the end user,
// use the StringComparison parameter on methods that have it to specify how to match strings.
bool ignoreCaseSearchResult = factMessage.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine($"Starts with \"extension\"? {ignoreCaseSearchResult} (ignoring case)");

bool endsWithSearchResult = factMessage.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine($"Ends with '.'? {endsWithSearchResult}");

上の例は、これらのメソッドを使用する重要なポイントを示しています。 既定では、検索で大文字と小文字が区別されます。 大文字と小文字を区別しない検索を指定する場合は、StringComparison.CurrentCultureIgnoreCase 列挙値を使用します。

検索対象テキストは文字列のどこにありますか?

IndexOf および LastIndexOf メソッドでは、文字列のテキストも検索します。 これらのメソッドは、検索されるテキストの場所を返します。 テキストが見つからない場合は、-1 が返されます。 次の例では、"methods" という単語の最初と最後の出現箇所の検索を示し、その間のテキストを表示します。

string factMessage = "Extension methods have all the capabilities of regular static methods.";

// Write the string and include the quotation marks.
Console.WriteLine($"\"{factMessage}\"");

// This search returns the substring between two strings, so
// the first index is moved to the character just after the first string.
int first = factMessage.IndexOf("methods") + "methods".Length;
int last = factMessage.LastIndexOf("methods");
string str2 = factMessage.Substring(first, last - first);
Console.WriteLine($"Substring between \"methods\" and \"methods\": '{str2}'");

正規表現を使用する特定のテキストの検索

文字列の検索には、System.Text.RegularExpressions.Regex クラスを使用できます。 これらの検索の複雑さは、単純なテキスト パターンから複雑なテキスト パターンまでさまざまです。

次のコード例では、文章内の "the" または "their" という単語を検索します (大文字と小文字の区別は無視されます)。 静的メソッドの Regex.IsMatch で検索を実行します。 検索対象の文字列と、検索パターンを指定します。 この例では、3 番目の引数で大文字と小文字を区別しない検索を指定します。 詳細については、「System.Text.RegularExpressions.RegexOptions」を参照してください。

検索パターンで検索対象のテキストを説明します。 次の表では、検索パターンの各要素について説明します (以下の表では、C# 文字列で \\ としてエスケープされる必要がある、単一の \ を使用します)。

パターン 説明
the テキスト "the" と一致
(eir)? "eir" の 0 個または 1 個の出現箇所と一致
\s 空白文字と一致
string[] sentences =
{
    "Put the water over there.",
    "They're quite thirsty.",
    "Their water bottles broke."
};

string sPattern = "the(ir)?\\s";

foreach (string s in sentences)
{
    Console.Write($"{s,24}");

    if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
    {
        Console.WriteLine($"  (match for '{sPattern}' found)");
    }
    else
    {
        Console.WriteLine();
    }
}

ヒント

string メソッドは、通常、正確な文字列を検索するときに選択することをお勧めします。 正規表現は、ソース文字列で何らかのパターンを検索する場合に適しています。

文字列はパターンに従っていますか?

次のコードでは正規表現を使用して、配列の各文字列の形式を検証します。 各文字列が電話番号の形式であることが検証されます。つまり、3 グループの数値がダッシュで区切られ、最初の 2 グループには 3 桁の数値が含まれ、3 つ目のグループには 4 桁の数値が含まれることが検証されます。 検索パターンでは正規表現の ^\\d{3}-\\d{3}-\\d{4}$ を使用します。 詳細については、「正規表現言語 - クイック リファレンス」をご覧ください。

パターン 説明
^ 文字列の先頭と一致
\d{3} 3 桁の文字と完全に一致
- '-' 文字と一致
\d{4} 4 桁の文字と完全に一致
$ 文字列の末尾と一致
string[] numbers =
{
    "123-555-0190",
    "444-234-22450",
    "690-555-0178",
    "146-893-232",
    "146-555-0122",
    "4007-555-0111",
    "407-555-0111",
    "407-2-5555",
    "407-555-8974",
    "407-2ab-5555",
    "690-555-8148",
    "146-893-232-"
};

string sPattern = "^\\d{3}-\\d{3}-\\d{4}$";

foreach (string s in numbers)
{
    Console.Write($"{s,14}");

    if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))
    {
        Console.WriteLine(" - valid");
    }
    else
    {
        Console.WriteLine(" - invalid");
    }
}

この単一の検索パターンは多くの有効な文字列と一致します。 単一のテキスト文字列ではなく、パターンの検索やパターンに対する検証を行う場合は、正規表現が適しています。

関連項目