C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The two options we use are RegexOptions.Multiline and RegexOptions.Singleline.
Regex.ReplaceRegexOptions.MultilineNote 2: My requirements were to trim the beginning and ending whitespace from a medium size (maybe several kilobytes) string.
C# program that trims with 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("]");
}
}
Output
[Some text]
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
}
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.
//
Note: Some programs focus on speed. But for many tasks, such as processing data in the background, Regex is ideal.
Regex