如何搜尋字串

您可以使用兩種主要策略來搜尋字串中的文字。 String 類別的方法會搜尋特定文字。 規則運算式會搜尋文字中的模式。

注意

本文中的 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。 選取 [執行] 按鈕以在互動式視窗中執行範例。 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。

字串類型,這是 System.String 類別的別名,提供一些有用的方法來搜尋字串的內容。 它們是 ContainsStartsWithEndsWithIndexOfLastIndexOfSystem.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 列舉值,來指定不區分大小寫的搜尋。

所搜尋文字在字串中的位置?

IndexOfLastIndexOf 方法也會搜尋字串中的文字。 這些方法會傳回所搜尋文字的位置。 如果找不到文字,則會傳回 -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 會執行搜尋。 您為其指定要搜尋的字串和搜尋模式。 在此情況下,第三個引數指定不區分大小寫的搜尋。 如需詳細資訊,請參閱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 方法通常是較好的選擇。 當您搜尋來源字串中的某個模式時,規則運算式是較好的選擇。

字串遵循模式嗎?

下列程式碼使用規則運算式來驗證陣列中每個字串的格式。 驗證需要每個字串具有電話號碼的形式,其中數字的三個群組以連字號分隔、前兩個群組包含三位數,而第三個群組包含四位數。 搜尋模式使用規則運算式 ^\\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");
    }
}

此單一搜尋模式會比對許多有效字串。 規則運算式較適合用來搜尋或驗證模式,而不是單一文字字串。

另請參閱