What are regular expressions in C#?

What is a regular expression?

A regular expression is essentially a string that represents a pattern. This pattern is processed by a regular expression engine and matched against a text to find its occurrence.

To process text using regular expressions, the regular expression engine needs at least two inputs:

  • A regular expression pattern
  • Text where we need to search this pattern

For example, we can find all phone numbers in a large text using a simple regular expression.

Finding all 10 digit numbers using Regex

Use of regular expressions

Regular expressions are an excellent tool for text processing. Regular expressions have a rich language, and allow us to look for complex patterns in a large body of text using the regular expression language.

We can perform “find and replace” operations efficiently with little code by using regular expressions. Regular expressions are very commonly used in user input validation (such as email addresses, credit card numbers, etc.)

Regular expressions in .NET

The .NET framework ships with a robust regular expression engine represented by the System.Text.RegularExpressions.Regex object. It is compatible with the Perl5 regular expression standard and has many additional functions.

Regex is one of the most important classes in the System.Text.RegularExpressions namespace. Some of the important methods of the Regex class include:

  • Regex.IsMatch(): This method is used to determine if the regex pattern occurs in the text or not.

  • Regex.Match(): This method returns information about the first occurrence of a matching pattern in the text.

  • Regex.Matches(): This method returns a collection representing information about all occurrences of a matching pattern in the input text.

  • Regex.Replace(): This method is used to replace the text that matches the regular expression pattern.

Free Resources