Loading ...

Regex: Replace replace uppercase letter with underscore and the letter | CodeAsp.Net

Regex: Replace replace uppercase letter with underscore and the letter

 /5
0 (0votes)

In this blog I will show how to replace uppercase letter with "underscore and the letter "in a string with REGEX. Let's say we have a string "ThisIsTestString" and we want to replace uppercase letter with "underscore and the letter" 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 = @"ThisIsTestString";


            string output = Regex.Replace(inputString, @"(?<!_)([A-Z])", "_$1"); ;

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

Output:

Below is the explanation of regex:

[_](?<!_)([A-Z])

Match the character “_” «[_]»
Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!_)»
   Match the character “_” literally «_»
Match the regular expression below and capture its match into backreference number 1 «([A-Z])»
   Match a single character in the range between “A” and “Z” «[A-Z]»


Created with RegexBuddy

Comments (no comments yet)

Top Posts