Regular Expressions In C#: 3 Examples You Need To Know
Tags: regex, csharp, coding, programming
Published: 2024-04-10 12:00:00

If you’re a beginner software developer then you may have already heard about regular expressions, but you might not have been able to put them into practice yet. No fear! In this article, I’ll walk you through 3 very simple examples of regular expressions in C# to get you started with using them.

No — I won’t be doing a deep dive into complex patterns and super wild and fancy things that you can do with regular expressions. Nope. Just some simple C# examples to get you pointed in the right direction!

{% embed https://weekly.devleader.ca/embed %} 

---

## **1 – Regex Starts With**

When working with regular expressions in C#, you can easily match strings that start with a specific pattern. This can be useful in scenarios where you need to find or extract strings that have a particular prefix. And yeah — I know you’re probably thinking “Hey Nick, don’t we already have `string.StartsWith` to use?” — and you’re right! But you can’t use that to [match patterns](https://www.devleader.ca/2024/04/01/regex-options-in-csharp-beginners-guide-to-powerful-pattern-matching/) more complex than a string directly.

To pattern match at the beginning of a string, you’ll need to use the caret (^) symbol as an anchor in your regular expression pattern. The caret symbol represents the start of a line or string in regular expressions, so by placing it at the beginning of your pattern, you ensure that the match you are looking for occurs at the start of the string.

To demonstrate this, consider the following code example:

```csharp
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 example, I’ve [created a list](https://www.devleader.ca/2024/03/20/mudblazor-list-items-how-to-create-awesome-blazor-list-views/) of input strings that we can exercise our regular expression against. We’ll use a caret at the beginning of the pattern, which otherwise just says “Hello”, so effectively we’re looking for strings that start with Hello. You can [try it out directly in your browser with this DotNetFiddle](https://dotnetfiddle.net/dA4MEI):

{% embed https://dotnetfiddle.net/dA4MEI %}

Now a question you *should* be asking yourself is… is this a good example of using a regular expression instead of string.StartsWith? What do you think the performance of this might be like? Try comparing them in BenchmarkDotNet to find out!

---

## **2 – Regex Ends With**

If you read the previous section: We’re talking about going the other way now. If you didn’t read the previous section: Go read that and then come back and read the first sentence in this section.

Choose your own adventure! And now we can discuss how to match the end of a string with our regex pattern. To match patterns that end with a particular string, we can use the dollar sign ($) symbol as an anchor in our regular expression pattern. The dollar sign represents the end of the string, ensuring that the specified [pattern is only matched](https://www.devleader.ca/2024/04/01/regex-options-in-csharp-beginners-guide-to-powerful-pattern-matching/) if it occurs at the end. Basically the opposite of what we saw with the caret symbol.

Let’s consider an example where we want to find all the words in a given text that end with the suffix “ing”. We can achieve this using regular expressions in C# with the following code snippet:

```csharp
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.");
}
```

Take note of the input strings above because all of them contain “ing” but not all of them end with “ing”. Which ones will match? If you want to try [the Regex ends with an example in your browser, check out this DotNetFiddle](https://dotnetfiddle.net/0LLhOA):

{% embed https://dotnetfiddle.net/0LLhOA %}

---

## **3 – Regex Is Match**

While we’ve been looking at comparisons to other string methods like StartsWith and EndsWith, we can continue this comparison with regex in C#. We know that regex will allow us to do more complex [pattern matching compared to these string method](https://www.devleader.ca/2023/10/01/the-builder-pattern-in-c-how-to-leverage-extension-methods-creatively/) variations, so what if we simply want to know if there’s a pattern match? If you wanted something similar to `string.Contains` just to know if a pattern matches a string, we can use the `Regex.IsMatch()` method to perform the pattern matching.

Note that `Regex.IsMatch()` will simply return a boolean result instead of a `Match` type. If you want more information about when your match succeeds, much like in the earlier examples, then you can just use the `Match` method or even the `Matches` to get all matching instances within the source string. I wanted to spice it up a bit and use this example just to compare to `string.Contains`, but if you wanted to compare it to something closer to `string.IndexOf` to find the position, switch back to the other methods.

If we don’t care about beginning or ending matching, we can ditch the ^ and $ symbols in our regular expressions. Let’s check out this code example that has a slightly more advanced pattern to match:

```csharp
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, the `Regex.IsMatch()` method takes in the `input` variable and the `pattern` variable was provided to the `Regex` instance at creation time. If you examine the pattern that we’re trying to match, we need to have at least 2 numbers with either 0 or many characters from a to z (case not being considered). But what about if we had 2 numbers that were separated by a character that wasn’t in the English alphabet? [Try it out for yourself with this DotNetFiddle](https://dotnetfiddle.net/UhguS9):

{% embed https://dotnetfiddle.net/UhguS9 %}

---

## **Wrapping Up Regular Expressions in CSharp**

As you can see from these examples, regular expressions in C# aren’t so scary, right? They’re just a little bit more complicated than doing some other string operations.

At least, on the surface.

There are [regex options in C#](https://www.devleader.ca/2024/04/01/regex-options-in-csharp-beginners-guide-to-powerful-pattern-matching/) to explore and, of course, the regular expressions that we write can get incredibly complex. Regular expressions can be a powerful tool for us to use, but keep in mind that you’ll want to balance things out. Consider readability, performance, and other characteristics if you start heavily relying on regular expressions for matching patterns in your applications!

If you found this useful and you’re looking for more learning opportunities, consider [subscribing to my free weekly software engineering newsletter](https://subscribe.devleader.ca/) and check out my [free videos on YouTube](https://www.youtube.com/@devleader?sub_confirmation=1)! Meet other like-minded software engineers and [join my Discord community](https://www.devleader.ca/discord-community-access/)!

{% embed https://weekly.devleader.ca/embed %} 

---

## **Want More Dev Leader Content?**

* Follow along on this platform if you haven’t already!    
* Subscribe to my free weekly software engineering and dotnet-focused newsletter. I include exclusive articles and early access to videos:  
    [**SUBSCRIBE FOR FREE**](https://subscribe.devleader.ca/)    
* Looking for courses? Check out my offerings:  
    [**VIEW COURSES**](https://devleader.ca/courses)    
* E-Books & other resources:  
    [**VIEW RESOURCES**](https://products.devleader.ca/)    
* Watch hundreds of full-length videos on my YouTube channel:  
    [**VISIT CHANNEL**](https://youtube.com/@devleader?sub_confirmation=1)    
* Visit my website for hundreds of articles on various software engineering topics (including code snippets):  
    [**VISIT WEBSITE**](https://devleader.ca/)    
* Check out the repository with many code examples from my articles and videos on GitHub:  
    [**VIEW REPOSITORY**](https://github.com/ncosentino/DevLeader)