Search Strings Using Regular Expressions

The System.Text.RegularExpressions.Regex class can be used to search strings. These searches can range in complexity from very simple to making full use of regular expressions. The following are two examples of string searching by using the Regex class.

class TestRegularExpressions
    static void Main()
        string[] sentences =
            "C# code",
            "Chapter 2: Writing Code",
            "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);

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

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: