none
Regex replace expression RRS feed

  • Question

  • I currently try to use Regex to replace the text to lower case for Html tags in string, here are my test codes:

    using System;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApp2
    {
        class Program
        {
            public static void Main()
            {
                string source = "<Div>Someone is here</Div>";
                Regex reg = new Regex(@"<(\/?)(\w+)>");
                Console.WriteLine(reg.Replace(source, @"<$1\L$2>"));
            }
        }
    }

    The console output result is: <\LDiv>Someone is here</\LDiv>, it seems it made the \L to a string.

    The same match expression and replace expression could work correctly in this website: https://regex101.com/ 

    BR.


    • Edited by William A Wang Thursday, October 24, 2019 10:00 AM spell issue
    Wednesday, October 23, 2019 3:55 PM

Answers

  • Check an alternative:

    string source = "<Div>Someone is here</Div>";
    Regex reg = new Regex( @"<(\/?)(\w+)>" );
    var result = reg.Replace( source, m => $"<{m.Groups[1].Value}{m.Groups[2].Value.ToLower( )}>" );
    Console.WriteLine( source );
    Console.WriteLine( result );
    

    Wednesday, October 23, 2019 4:27 PM

All replies

  • Check an alternative:

    string source = "<Div>Someone is here</Div>";
    Regex reg = new Regex( @"<(\/?)(\w+)>" );
    var result = reg.Replace( source, m => $"<{m.Groups[1].Value}{m.Groups[2].Value.ToLower( )}>" );
    Console.WriteLine( source );
    Console.WriteLine( result );
    

    Wednesday, October 23, 2019 4:27 PM
  • Notice the documentation for Regex.Replace:

    Note

    Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Wednesday, October 23, 2019 10:26 PM
  • That is a good solution, thanks.
    Thursday, October 24, 2019 9:59 AM
  • T.T  .
    Thursday, October 24, 2019 9:59 AM
  • Hi William A Wang,

    Is your problem solved? If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, October 25, 2019 1:29 AM
    Moderator