C# Regex Trim Example

Regex type

Regex can be used to trim whitespace. Trimming a string removes whitespace and leaves only the important contents. Several methods are available, each with pluses and minuses. We trim strings using Regex in the C# programming language.

These C# examples show how to remove whitespace from strings with Regex.Replace and patterns.

Example

Note

Regexes are very powerful, but also very powerful in giving me headaches. One problem I encountered was a multiple-line string. With Regex, you must indicate how you want the engine to treat newlines (\n). The two options are RegexOptions.Multiline and RegexOptions.Singleline. My requirements were to trim the beginning and ending whitespace from a medium size (maybe several kilobytes) string. Here's one method that uses two passes.

Program that trims with Regex [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
	//
	// Example string
	//
	string source = "  Some text ";
	//
	// Use the ^ to always match at the start of the string.
	// Then, look through all WHITESPACE characters with \s
	// Use + to look through more than 1 characters
	// Then replace with an empty string.
	//
	source = Regex.Replace(source, @"^\s+", "");

	//
	// The exact same as above, but with a $ on the end.
	// This requires that we match at the end.
	//
	source = Regex.Replace(source, @"\s+$", "");

	Console.Write("[");
	Console.Write(source);
	Console.WriteLine("]");
    }
}

Output

[Some text]

Compile the Regexes

Readers have commented on compiled Regex objects, and they do make a substantial performance improvement. My quick tests showed that for using two compiled regexes 1,000 times each was about 47% faster than not compiling them. However, as I will show next, this was a "drop in the bucket."

Fragment that shows compiled Regex [C#]

//
// Use two precompiled Regexes.
//
Regex a1 = new Regex(@"^\s+", RegexOptions.Compiled);
Regex a2 = new Regex(@"\s+$", RegexOptions.Compiled);

foreach (object item in _collection) // Example loop.
{
    //
    // Reuse the compiled regex objects over and over again.
    //
    string source = "  Some text ";
    source = a1.Replace(source, "");
    source = a2.Replace(source, ""); // compiled: 3620
}

Another Regex approach

Here we look at another way you can trim strings using Regex. What if we could combine the two above regular expressions into a single one, and then compile that? Well, we certainly can do that, and I wrote the code.

Fragment that shows alternate syntax [C#]

string source = "  Some text ";

//
// Use the alternate syntax "|" for combining both regexes.
//
source = Regex.Replace(source, @"^\s+|\s+$", "");

//
// Same as before but with the two alternates switched.
// source = Regex.Replace(source, @"\s+$|^\s+", "");
// ... we could compile all of these too.
//

What's best?

Question and answer

Here we need a balance between development time and how much code you want to write. If you need Trim() with different requirements than the built-in methods, then the Regex methods will be faster to write. If it is at all reasonable for you to use the built-in Trim(), do so.

Trim String Tips

Summary

The C# programming language

We looked at some methods of trimming the starts and ends of strings using the System.Text.RegularExpressions namespace in the C# programming language. For my projects where I consider performance critical, I don't use Regex. ASP.NET developers need to make their pages feel nearly instant, but for some other tasks such as processing data in the background Regex is ideal.

Regex Type
.NET