Devi Devi - 24 days ago 9
C# Question

How to replace a particular string in c# using regex or linq

I have a string where I need to replace a particular string, my string is as follows

string s = @"-Username ABC **-Password XYZ** -Address MNO";
string[] s1 = s.Split('-');
var newList = s1.Where(s2 =>s2.Contains("Password"));


I need to replace the string
-Password XYZ
to
-Password ****
can some one help me

Answer

Test

    [TestCase("-Username ABC -Password XYZ -Address MNO", "-Username ABC -Password *** -Address MNO")]
    public void Test(string toTest, string expected ) 
    {
        Assert.AreEqual(expected, DestroyPassword(toTest));
    }

Code

    public static string DestroyPassword(string str )
    {
          var r = new Regex("-Password .*? ");//? in .net means not greedy
          return r.Replace(str, "-Password *** ");
    }