可以使用 System.Text.RegularExpressions.Regex 类搜索字符串。这些搜索可以涵盖从非常简单到全面使用正则表达式的复杂范围。以下是使用 Regex 类搜索字符串的两个示例。有关更多信息,请参见 .NET Framework 正则表达式

示例

以下代码是一个控制台应用程序,用于对数组中的字符串执行简单的不区分大小写的搜索。给定要搜索的字符串和包含搜索模式的字符串后,静态方法 System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions) 执行搜索。在本例中,使用第三个参数指示忽略大小写。有关更多信息,请参见 System.Text.RegularExpressions.RegexOptions

C# CopyCode image复制代码
class TestRegularExpressions
{
    static void Main()
    {
        string[] sentences = 
        {
            "cow over the moon",
            "Betsy the Cow",
            "cowering in the corner",
            "no match here"
        };

        string sPattern = "cow";

        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();
            }
        }
    }
}

输出

 
       cow over the moon  (match for 'cow' found)
           Betsy the Cow  (match for 'cow' found)
  cowering in the corner  (match for 'cow' found)
           no match here

以下代码是一个控制台应用程序,此程序使用正则表达式验证数组中每个字符串的格式。验证要求每个字符串具有电话号码的形式,即用短划线将数字分成三组,前两组各包含三个数字,第三组包含四个数字。这是通过正则表达式 ^\\d{3}-\\d{3}-\\d{4}$ 完成的。有关更多信息,请参见正则表达式语言元素

C# CopyCode image复制代码
class TestRegularExpressionValidation
{
    static void Main()
    {
        string[] numbers = 
        {
            "123-456-7890", 
            "444-234-22450", 
            "690-203-6578", 
            "146-893-232",
            "146-839-2322",
            "4007-295-1111", 
            "407-295-1111", 
            "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");
            }
        }
    }
}

输出

 
    123-456-7890 - valid
    444-234-22450 - invalid
    690-203-6578 - valid
    146-893-232 - invalid
    146-839-2322 - valid
    4007-295-1111 - invalid
    407-295-1111 - valid
    407-2-5555 - invalid

请参见