Regex.Replace End Example (String)
This page was last reviewed on 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.
Shows a regex
The end-matching metacharacter yields some capabilities that are hard to duplicate. It can make programs simpler and easier to maintain.
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.
Shows a regex
<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.
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 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 May 14, 2023 (edit).
© 2007-2024 Sam Allen.