Thursday, August 15, 2013

CSharp C# Regular Expression REPLACE example

CSharp C# Regular Expression REPLACE example

using System;
using System.Text.RegularExpressions;

class Stuff4
{
    static void Main()
    {
        /*
             Before:  A hiker is not a climber
            After :  A hotter is not a climber
            [replace "iker" with "otter"]

            - This example passes in the string "A hiker is not a climber",

            - Then we pass in a RegEx search pattern "(.*)(iker)(.*)" that:
                Takes any character any number of times until we find "iker" so
                it will return "A h" as the first find (a/k/a $1). 
                And "iker" will be $2.  Finally, any character, after "iker", any
                number of times, which is " is not a climber" (a/k/a $3)

            - Then we pass in a RegEx string that describes how we want the matches
                reconstructed with "$1otter$3":
                    - Start by picking up $1: "A h"
                    - Then add the arbitrary string "otter" (and skip $2 ["iker"]
                    - Finally, add $3: " is not a climber"

            - We get the reconstructed string: "A hotter is not a climber"
         *
         * ACTUAL OUTPUT:
                A hiker is not a climber
                A hotter is not a climber
         */
        string inputNow = "A hiker is not a climber";
        string outputNow = Regex.Replace(inputNow, "(.*)(iker)(.*)", "$1otter$3");       
        Console.WriteLine(inputNow);
        Console.WriteLine(outputNow);
        Console.ReadLine();
    }
}


No comments:

Post a Comment