C# Regex

Summary: in this tutorial, you will learn how to use the C# Regex class to work with regular expressions.

Introduction to the C# Regex class

The following simple program uses the Contains() method of a String object to check whether an input string contains the number 2:

using static System.Console;


var message = "I have 2 apples";
var result = message.Contains("2");

WriteLine(result);Code language: C# (cs)

Output:

TrueCode language: C# (cs)

If the number that you want to check is not 2 but may vary from 0 to 9, then you need to modify the program like this:

var message = "I have 5 apples";

var result = false;
for (var i = 0; i <= 9; i++)
{
    if (message.Contains(i.ToString()))
    {  
        result = true;
        break;
    }
}

WriteLine(result);Code language: C# (cs)

The program sets the result flag to false and checks if an input string contains a single digit from 0 to 9 using a for loop. If it does, the program sets the result to true and breaks the loop. Finally, the program writes the result to the console.

The program works as expected but it is quite verbose. To check if a string contains a single digit, you can use a regular expression.

A regular expression describes a pattern for matching. For example, to match a single digit, you use the following pattern:

\dCode language: C# (cs)

To use this regular expression pattern in C# for matching, you will need to utilize the Regex class.

First, import the System.Text.RegularExpressions namespace in the program:

using System.Text.RegularExpressions;Code language: C# (cs)

Second, create a new Regex object and pass the regular expression pattern to the Regex‘s constructor:

var regex = new Regex(@"\d");Code language: C# (cs)

Second, call the IsMatch() method that returns true if an input string matches the regular expression pattern:

var result = regex.IsMatch(message);Code language: C# (cs)

If the input string message doesn’t match the pattern, the IsMatch() method returns false.

Put it all together:

using System.Text.RegularExpressions;
using static System.Console;


var message = "I have 5 apples";
var regex = new Regex(@"\d");

var result = regex.IsMatch(message);

WriteLine(result);Code language: C# (cs)

Output:

TrueCode language: C# (cs)

In this example, by using regular expressions to match, the program becomes less verbose.

Using C# Regex.IsMatch() static method

Besides creating a new Regex object and calling the IsMatch() method, you can use the IsMatch() static method of the Regex class. For example:

using System.Text.RegularExpressions;
using static System.Console;


var message = "I have 5 apples";
var pattern = @"\d";

var result = Regex.IsMatch(message, pattern);

WriteLine(result);Code language: C# (cs)

Output:

TrueCode language: C# (cs)

The IsMatch() static method accepts two arguments, the first one is an input string and the second one is a pattern to match.

If you have a one-time matching task, the IsMatch() static method is more concise and convenient. However, when you need to reuse the same pattern for multiple matches, using the IsMatch() method of a Regex object offers better performance.

The reason is that when you call the IsMatch() method of a Regex object, it compiles the pattern into an internal representation that is optimized the pattern for matching. Once compiled, the Regex object caches the result internally so that the next match will not need to recompile the pattern again, resulting in faster matching.

On the other hand, the IsMatch() static method doesn’t provide the same optimizations. Instead, it compiles the regular expression pattern internally for each matching operation. This causes extra overhead and decreases performance if you use the same pattern for matching multiple times.

Notice that this logic is also applied to other methods and static methods of the Regex class like Match() and Matches().

C# Regex Match method

The Match() method matches a pattern and returns the first match as a single Match object.

For example, the following program uses the Match() method to output the first number found in a string:

using System.Text.RegularExpressions;
using static System.Console;


var message = "I have 3 apples and 5 oranges";
var pattern = @"\d";

var match = Regex.Match(message, pattern);
WriteLine(match);Code language: C# (cs)

Output:

3Code language: C# (cs)

C# Regex Matches method

Unlike the Match() method, the Matches() method returns a collection of matches found in a string. For example:

using System.Text.RegularExpressions;
using static System.Console;


var message = "I have 3 apples and 5 oranges";
var pattern = @"\d";

var matches = Regex.Matches(message, pattern);

foreach (var match in matches)
{
    Console.WriteLine(match);
}Code language: C# (cs)

Output:

3
5Code language: C# (cs)

In this tutorial, you learned a simple pattern that matches a single digit. In the next tutorials, you will learn how to construct more flexible patterns.

Summary

  • Use Regex.IsMatch() method to check if a regular expression pattern finds a match in a string.
  • Use Regex.Match() method to return the first match of a regular expression pattern in a string.
  • Use Regex.Matches() method to return all matches of a regular expression pattern in a string.
  • Use methods like IsMatch(), Match(), and Matches() of the Regex object if you match a single pattern multiple times to gain higher performance. Otherwise uses the corresponding static methods of the Regex class to make the code more concise.
Was this tutorial helpful ?