TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Regex.Replace String End

This 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

Input and output required

Input string: This string has something at the end<br/>
      Output: This string has something at the end

Example. 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 Method

Note: We combine it with the "$" character at the end, which signals the end of the string.

C# program that removes string

using System;

class Program
{
    static void Main()
    {
	// 1
	// The string you want to change.
	string s1 = "This string has something at the end<br/>";

	// 2
	// Use regular expression to trim the ending string.
	string s2 = System.Text.RegularExpressions.Regex.Replace(s1, "<br/>$", "");

	// 3
	// Display the results.
	Console.WriteLine("\"{0}\"\n\"{1}\"",
	    s1,
	    s2);
    }
}

Output

"This string has something at the end<br/>"
"This string has something at the end"

In step 1, we declare a new string that contains an ending substring we need to remove. In step 2, we call the Regex.Replace static method. In step 3, we display the resulting string copy, which has been stripped of the ending string.

Console.WriteLine

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.

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. I recommend using string-based methods for when performance is critical.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf