Note 2 My requirements were to trim the beginning and ending whitespace from a medium size (maybe several kilobytes) string.
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+$", "");
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.
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.