Regex
, trimRegex
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.
One problem we might encounter is multiple-line strings. With Regex
, we can indicate how we want the engine to treat newlines (\n).
string
. The next metacharacter then matches whitespace.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]
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.
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.