[英]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 我需要将字符串-Password XYZ
替换为-Password ****
可以帮助我一些人
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: 如果您知道-Address
始终是下一个令牌,那么这样的事情会更好:
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' 但是当密码包含'-Address'时,事件不能很好地处理
You can use Regex.Replace(input, replacement). 您可以使用Regex.Replace(输入,替换)。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.