Home
C#
Regex Trim Example
This page was last reviewed on Oct 28, 2021.
Dot Net Perls
Regex, trim. Regex can be used to trim whitespace. Trimming a string removes whitespace and leaves only the important contents.
Shows a regex
C# method info. Several methods 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, you must indicate how you want the engine to treat newlines (\n).
Note The two options we use are RegexOptions.Multiline and RegexOptions.Singleline.
RegexOptions.Multiline
Note 2 My requirements were to trim the beginning and ending whitespace from a medium size (maybe several kilobytes) string.
Shows a regex
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 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("]"); } }
[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.
Start: ^\s+ End: \s+$ Both: ^\s+|\s+$
Compiled. Compiled regexes 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.
RegexOptions.Compiled
Discussion. If you need Trim with different requirements than the built-in methods, the Regex methods will be easier. If it is at all reasonable for you to use the built-in Trim, do so.
String Trim
String TrimEnd, TrimStart
Summary. We looked at some methods of trimming the starts and ends of strings using Regex in the C# language. For many tasks, such as processing data in the background, Regex is ideal.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 28, 2021 (image).
Home
Changes
© 2007-2024 Sam Allen.