In C#, regular expressions are represented by the `Regex` class, which is part of the `System.Text.RegularExpressions` namespace.
To use regular expressions in C#, you would first create a `Regex` object by calling its constructor and passing in the pattern you want to match. For example:
“`csharp
Regex regex = new Regex(@”\b\d{3}-\d{3}-\d{4}\b”);
“`
In this example, the regular expression pattern `\b\d{3}-\d{3}-\d{4}\b` matches a string that represents a phone number in the format “###-###-####”.
Once you have created a `Regex` object, you can use its various methods to search for matches in a string. The most commonly used methods are `Match` and `Matches`.
The `Match` method returns the first occurrence of a pattern in a string. For example:
“`csharp
string input = “My phone number is 123-456-7890.”;
Match match = regex.Match(input);
if (match.Success)
{
Console.WriteLine(“Phone number found: ” + match.Value);
}
“`
The `Matches` method returns all occurrences of a pattern in a string. For example:
“`csharp
string input = “My phone numbers are 123-456-7890 and 987-654-3210.”;
MatchCollection matches = regex.Matches(input);
foreach (Match match in matches)
{
Console.WriteLine(“Phone number found: ” + match.Value);
}
“`
In addition to `Match` and `Matches`, the `Regex` class also provides other methods for performing operations such as replacing patterns in a string or splitting a string based on a pattern.
Regular expressions in C# support a wide variety of patterns and options. You can find more information and examples in the official documentation: https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
It’s also worth noting that C# provides a convenient way to work with regular expressions using the `string` class’s `Regex` static methods, such as `Regex.IsMatch` and `Regex.Replace`. These methods allow you to perform simple regex operations without explicitly creating a `Regex` object. For example:
“`csharp
string input = “My phone number is 123-456-7890.”;
bool isMatch = Regex.IsMatch(input, @”\b\d{3}-\d{3}-\d{4}\b”);
if (isMatch)
{
Console.WriteLine(“Phone number found.”);
}
string replacedInput = Regex.Replace(input, @”\b\d{3}-\d{3}-\d{4}\b”, “[phone number]”);
Console.WriteLine(“Replaced input: ” + replacedInput);
“`