Regex.Replace
, string
endA 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.
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.
<br/> Match BR html self-closing element. $ Match end of string.
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
.
string
that contains an ending substring we need to remove. This is what we will use Regex
upon.Regex.Replace
static
method. We pass 3 arguments to Regex.Replace
.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"
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.