Mastering Regular Expressions in C#: Essential Examples
Written on
Chapter 1: Introduction to Regular Expressions
As an aspiring software developer, you may have encountered the concept of regular expressions. While they can seem intimidating, this article will simplify them for you by presenting three straightforward examples using C#.
These examples are designed to help you grasp the basics without delving into the more intricate aspects of regular expressions. Let's get started!
Section 1.1: Regex for String Starting Patterns
In C#, you can effectively identify strings that begin with a specific sequence using regular expressions. This technique is particularly useful when searching for or extracting strings with a defined prefix. You might wonder, "Isn't there a string method for that?" You're correct! However, string methods do not accommodate pattern matching beyond simple strings.
To detect a pattern at the start of a string, utilize the caret (^) symbol in your regex. This symbol signifies the beginning of a line or string, ensuring that your match occurs right at the start.
Consider this illustrative code example:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
List<string> inputs = new()
{
"Hello, World!",
"Something something Hello!",
" Hello",
"Hello from Dev Leader!",
};
string pattern = "^Hello";
Regex regex = new Regex(pattern);
foreach (var input in inputs)
{
Match match = regex.Match(input);
Console.WriteLine(
$"'{input}' {(match.Success ? "did" : "did not")} " +
"match the string starting with the pattern.");
}
In this snippet, we’ve created a list of strings to test our regex pattern against. By placing the caret at the beginning, we are effectively looking for strings that commence with "Hello". Curious to see how it works? You can run it in your browser via this DotNetFiddle.
Now, consider whether this is an appropriate use of regex compared to string.StartsWith. What do you think about its performance? Test it out with BenchmarkDotNet!
Section 1.2: Regex for String Ending Patterns
Building on the previous section, let's explore how to match the end of a string. To find strings that conclude with a specific sequence, use the dollar sign ($) as your regex anchor. This symbol indicates the end of a string and ensures that your match occurs solely at the conclusion.
For instance, if we want to identify all words ending in "ing," we can implement the following C# code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
List<string> inputs = new()
{
"Coding", // match
"I love programming!", // no match
"Coding is fun!", // no match
"I love programming", // match
};
string pattern = "ing$";
Regex regex = new Regex(pattern);
foreach (var input in inputs)
{
Match match = regex.Match(input);
Console.WriteLine(
$"'{input}' {(match.Success ? "did" : "did not")} " +
"match the string ending with the pattern.");
}
Review the input strings; while all contain "ing," only some end with it. Want to test the regex for ending patterns? Check out this DotNetFiddle!
Chapter 2: Regex for Pattern Matching
When comparing regex with string methods like StartsWith and EndsWith, we can also use regex to determine if a pattern exists within a string. For this purpose, the Regex.IsMatch() method serves well, functioning similarly to string.Contains by returning a boolean value.
Unlike previous methods, IsMatch() does not provide a Match type but offers a simple true or false response. If you require more detail regarding your match, you can utilize the Match or Matches methods for comprehensive results.
In cases where the position of the match doesn’t matter, you can omit the ^ and $ symbols from your regex. Here’s a more advanced example that targets a specific pattern:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
List<string> inputs = new()
{
"Nick", // no match
"Nick1", // no match
"1Nick", // no match
"Nick42", // match
"42Nick", // match
"4Nick2", // match
"42", // match
"1337", // match
"6", // no match
};
string pattern = "[0-9]+[a-zA-Z]*[0-9]+";
Regex regex = new Regex(pattern);
foreach (var input in inputs)
{
bool isMatch = regex.IsMatch(input);
Console.WriteLine(
$"'{input}' {(isMatch ? "did" : "did not")} " +
"match the pattern.");
}
In this example, we check for inputs that contain at least two numbers, optionally followed by letters. Want to experiment with this pattern? Try it on DotNetFiddle.
Wrapping Up Regular Expressions in C#
These examples demonstrate that regular expressions in C# aren’t as daunting as they may appear. They simply require a bit more understanding compared to standard string operations.
While regex offers powerful capabilities, remember to weigh readability, performance, and complexity when incorporating them into your applications.
If you found this guide useful and are eager for more insights, consider subscribing to my free weekly software engineering newsletter, and check out my YouTube videos for additional learning opportunities! Connect with other developers in my Discord community!
Want More Dev Leader Content?
Follow along if you haven’t already! Subscribe to my free weekly software engineering and .NET-focused newsletter for exclusive articles and early access to videos:
- Subscribe for Free
Looking for courses? Explore my offerings:
- View Courses
Check out e-books and other resources:
- View Resources
Watch hundreds of full-length videos on my YouTube channel:
- Visit Channel
Visit my website for a plethora of articles on various software engineering topics, including code snippets:
- Visit Website
Discover the repository with numerous code examples from my articles and videos on GitHub:
- View Repository
Explore the video titled "Regular Expressions in C" for a deeper understanding of regex in programming.