Loading ...

Regex: Replace replace underscores with hyphens | CodeAsp.Net

Regex: Replace replace underscores with hyphens

 /5
0 (0votes)

In this blog I will show how to replace underscores with hyphens in a string with REGEX. Let's say we have a string "This_is_test_string" and we want to replace underscores with hyphens so that the output comes "This-is-test-string". Below is the sample code to do the same:

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            const string inputString = @"This_is_test_string";


            string output = Regex.Replace(inputString, @"[_]", "-"); ;

            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
}


Output:

Below is the explanation of regex:

[_]

Match the character “_” «[_]»


Created with RegexBuddy

Comments (no comments yet)

Top Posts