Home
C#
Regex.Replace End Example (String)
Updated May 14, 2023
Dot Net Perls
Regex.Replace, string end. A C# Regex can change the ends of certain strings. With the Regex.Replace method, we use the "$" metacharacter to match the string end.
The end-matching metacharacter yields some capabilities that are hard to duplicate. It can make programs simpler and easier to maintain.
Regex.Replace
Regex.Match
Pattern details. 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.
<br/> Match BR html self-closing element. $ Match end of string.
Example code. The solution we see here uses the Regex.Replace method. 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
using System; // Step 1: the string you want to change. string s1 = "This string has something at the end<br/>"; // Step 2: use regular expression to trim the ending string. string s2 = System.Text.RegularExpressions.Regex.Replace(s1, "<br/>$", ""); // Step 3: display the results. Console.WriteLine("\"{0}\"\n\"{1}\"", s1, s2);
"This string has something at the end<br/>" "This string has something at the end"
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 14, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen