Search⌘ K
AI Features

Regular Expressions

Explore the basics of regular expressions in C# to simplify text processing tasks. Learn how to find matching substrings, validate string formats like emails, and improve performance with compile-time regex using [GeneratedRegex]. This lesson provides a foundational overview to enhance your string handling skills in .NET.

A .NET application can use the power of regular expressions out of the box. Regular expressions are a versatile and effective way to process large texts.

Note: Regular expressions require a separate course of their own because of their complexity. This lesson only provides a brief overview.

We can use them to find substrings that match a certain condition. We can also check whether a string object conforms to specific rules, such as a correct phone number format. Regular expressions require far less code to address these tasks than the built-in methods of the System.String and StringBuilder classes.

Finding matches using string methods

Suppose we need to find all words containing the "or" substring within a large block of text. We can implement a solution using standard string methods.

Here is a traditional approach using manual iteration.

C# 14.0
using System.Collections.Generic;
// The text we need to scan
var text = "Hello world! I am using this string to store some valuable information.";
// We first split the text into separate words
var wordsInText = text.Split();
var matches = new List<string>();
// We then iterate through the array of words
// and check if the word contains 'or'
foreach (var word in wordsInText)
{
if (word.Contains("or"))
{
// We collect matches in a separate list
matches.Add(word);
}
}
// If there were matches, we print them out
if (matches.Count > 0)
{
foreach (var word in matches)
{
Console.WriteLine(word);
}
}
else
{
Console.WriteLine("No matches found.");
}
  • Line 4: We declare a variable holding the target text.

  • Line 7: We split the text into an array of individual words.

  • Line 8: We create a list to store our matching results.

  • Lines 12–19: We loop through each word and add it to our list if it contains the “or” ...