Share via

C# String.Replace() & Regex.Replace() not working at my end

T.Zacks 3,996 Reputation points
2021-05-16T08:35:12.347+00:00

see this code example
string maindata = "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";
string data = "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";

            //data = Regex.Escape(data);

            string strformula = Regex.Replace(maindata, "\"" + data.Replace("(", "\\(").Replace(")", "\\)").Replace("$", "\\$") + "\"", "W51",RegexOptions.IgnoreCase);
            strformula = maindata.Replace("\"" + data.Replace("(", "\\(").Replace(")", "\\)").Replace("$", "\\$") + "\"", "W51");

Regex.Escape(data); also does not work.

i really do not understand the reason behind why this replace is getting fail ? please guide me what is lacking there ?

EDIT


string maindata = "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";
string data =     "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";
string strformula = Regex.Replace(maindata, data , "W51",RegexOptions.None);

try my above code and must notice replace not able to replace Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999 with W51

Thanks

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

  1. T.Zacks 3,996 Reputation points
    2021-05-16T09:44:26.377+00:00

    I got the solution. here is code which is working now. this one help to sort the issue Regex.Replace(maindata, @"[^\w\d]", "_");

    string maindata = "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";  
    string data = "Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";     
          
    string modifiedMainData = Regex.Replace(maindata, @"[^\w\d]", "_");  
    string modifiedData = Regex.Replace(data, @"[^\w\d]", "_");  
          
          
    string finalResult = Regex.Replace(modifiedMainData, modifiedData, "W51", RegexOptions.None);  
    

    This is another approach which worked.

                string maindata = @"Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";   
                string data = @"Operational Metrics~Domestic Subscribers Disney+~2015 FY~9999";   
                data = Regex.Escape(data);  
                string strformula = Regex.Replace("\"" + maindata + "\"", "\"" + data.Replace("(", "\\(").Replace(")", "\\)").Replace("$", "\\$") + "\"", "W51", RegexOptions.None);  
    
    
      
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.