C# Regex.Replace, Matching End of StringThis C# example program uses the Regex.Replace method. It changes the end of a string.
Regex.Replace, string end.
Regex can change the ends of certain strings. With the Regex.Replace method, we use the "$" metacharacter to match the string end. This yields some capabilities that are hard to duplicate.Regex.Replace
First, we can use regular expressions to remove the ending part of a string. The solution we see here uses the Regex.Replace static method, which is convenient but not optimally fast.Static
Note: We combine it with the "$" character at the end, which signals the end of the string.
Step 1: We declare a new string that contains an ending substring we need to remove. This is what we will use Regex upon.
Step 2: Here we invoke the Regex.Replace static method. We pass 3 arguments to Regex.Replace.
Step 3: We display the resulting string copy, which has been stripped of the ending string.Console.WriteLine
C# program that removes string
static void Main()
// The string you want to change.
string s1 = "This string has something at the end<br/>";
// Use regular expression to trim the ending string.
string s2 = System.Text.RegularExpressions.Regex.Replace(s1,
// Display the results.
"This string has something at the end<br/>"
"This string has something at the end"
Notes on regular expression.
The "$" metacharacter shown in the Regex.Replace method call forces the string in the pattern to occur at the end of the input string for the Replace to take effect.
Note: This means that the pattern won't be replaced if it occurs anywhere else in the string.
We replaced a substring that occurs at the end of an input string. This is useful for stripping markup or ending sequences that you don't want. I recommend using string-based methods for when performance is critical.Regex
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.