Share via


HOW TO:使用規則運算式搜尋字串 (C# 程式設計手冊)

System.Text.RegularExpressions.Regex 類別可用來搜尋字串。 這些搜尋的複雜度範圍,可能介於非常簡單到充分使用規則運算式之間。 下列是使用 Regex 類別搜尋字串的兩個範例。 如需詳細資訊,請參閱 .NET Framework 規則運算式

範例

下列程式碼是主控台應用程式,會在陣列中執行不區分大小寫的簡單字串搜尋。 Regex.IsMatch 靜態方法會執行搜尋 (提供要搜尋的字串及包含搜尋模式的字串)。 在上述情形中,會使用第三個引數表示應該忽略大小寫。 如需詳細資訊,請參閱 System.Text.RegularExpressions.RegexOptions

class TestRegularExpressions
{
    static void Main()
    {
        string[] sentences = 
        {
            "C# code",
            "Chapter 2: Writing Code",
            "Unicode",
            "no match here"
        };

        string sPattern = "code";

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

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

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();

    }
}
/* Output:
           C# code  (match for 'code' found)
           Chapter 2: Writing Code  (match for 'code' found)
           Unicode  (match for 'code' found)
           no match here
*/

下列程式碼是一個主控台應用程式,會使用規則運算式驗證陣列中每個字串格式。 驗證需要每個字串都使用電話號碼的格式,其中三組數字之間都以破折號分隔,前兩組包含三個數字而第三組包含四個數字。 這可以使用規則運算式 ^\\d{3}-\\d{3}-\\d{4}$ 來完成。 如需詳細資訊,請參閱規則運算式語言項目

class TestRegularExpressionValidation
{
    static void Main()
    {
        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", 
        };

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

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

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

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
      123-555-0190 - valid
     444-234-22450 - invalid
      690-555-0178 - valid
       146-893-232 - invalid
      146-555-0122 - valid
     4007-555-0111 - invalid
      407-555-0111 - valid
        407-2-5555 - invalid
*/

請參閱

概念

C# 程式設計手冊

字串 (C# 程式設計手冊)