Home
C#
Regex Trim Example
Updated Mar 5, 2025
Dot Net Perls
Regex, trim. Regex in C# can be used to trim whitespace. Trimming a string removes whitespace and leaves only the important contents.
Several methods for trimming strings are available, each with pluses and minuses. We trim strings using Regex in the C# programming language.
Regex.Match
Example. One problem we might encounter is multiple-line strings. With Regex, we can indicate how we want the engine to treat newlines (\n).
RegexOptions.Multiline
Part 1 We use a metacharacter to match at the start of a string. The next metacharacter then matches whitespace.
Part 2 We use the dollar sign at the end to match the end of a string. This trims the end of the string.
using System; using System.Text.RegularExpressions; string source = " Some text "; // Part 1: use the ^ to match at the start. // ... 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+", ""); // Part 2: trim with a $ on the end. // ... This requires that we match at the end. source = Regex.Replace(source, @"\s+$", ""); Console.WriteLine($"[{source}]");
[Some text]
Combined Regex. Here we look at another way you can trim strings using Regex. We combine the 2 regular expressions into one, and then use a single Regex Replace call.
using System; using System.Text.RegularExpressions; // Use both regular expressions at once. string source = " cat\n"; source = Regex.Replace(source, @"^\s+|\s+$", ""); Console.WriteLine($"[{source}]");
[cat]
If you need Trim with different requirements than the built-in methods, the Regex methods will be easier. If it is reasonable to use the built-in Trim, this is preferable.
String Trim
String TrimEnd, TrimStart
With Regex in the C# language we can trim the starts and ends of strings. For many tasks, such as processing data in the background, Regex is ideal.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 5, 2025 (new example).
Home
Changes
© 2007-2025 Sam Allen