1

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

2 Answers 2

2

Test

    [TestCase("-Username ABC -Password XYZ -Address MNO", "-Username ABC -Password *** -Address MNO")]
    [TestCase("-Username ABC -Password XYZ", "-Username ABC -Password ***")]
    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 ***$1");
    }

EDIT:

Word of caution

This doesn't mask passwords with spaces in them. If you know that -Address is always the next token then something like this will be better:

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

but event that doesn't deal well with the case when the password contains '-Address'

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Regex.Replace(input, replacement). Function will replace all values found by regex expression.

string input = @"-Username ABC **-Password XYZ** -Address MNO";
string pattern = "(-Password )(\S+)";
string replacement = "$1****";
Regex regex = new Regex(pattern);
string result = regex.Replace(input, replacement);

3 Comments

My result as per your code -Username ABC ****** -Address MNO expected is -Username ABC -Password ****** -Address MNO
This gets rid of the whole '-Password XYZ** ' chuck.
You're missing @ before the pattern. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.