我有一个像网站的密码是钱
这样的字符串,现在如果该字符串包含单词“money”
那么我必须屏蔽该字符串,例如网站密码是XXXXX
。替代 XXXXX
长度应根据 money
的长度而变化,即,如果字符串是 The Password for the website is Moneyyyyy
那么我的输出应该网站密码是 XXXXXXXXX
到目前为止我尝试过这样
string content="The Password for the website is money";
string pattern = @"\bmoney\b";
string replace = "XXXXX";
content = Regex.Replace(content, pattern, replace);
但没有结果,我什至尝试使用字符串替换而不是正则表达式,但没有用。 这个你能帮我吗。
最佳答案
您需要使用带有 Regex.Replace
的匹配评估器和正则表达式来匹配内部带有键的任何单词,例如 \w*money\w*
:
var content="The Password for the website is money and moneyyyy";
var key = "money";
var pattern = string.Format(@"\w*{0}\w*", Regex.Escape(key));
var mask = 'X';
content = Regex.Replace(content, pattern, m => new string(mask, m.Value.Length));
Console.WriteLine(content);
// => The Password for the website is XXXXX and XXXXXXXX
请参阅C# demo
正则表达式的含义是:
\w*
- 零个或多个(*
是匹配零个或多个量化子模式实例的量词)单词字符(字母、数字和_
符号)。注意,如果您将其替换为\p{L}*
,则可以调整此部分以仅匹配字母(或者如果您只需要 ASCII,请使用[a-zA-Z]*
.money
-key
,如果里面有特殊符号,您可能需要Regex.Escape
它\w*
- 见上文。
关于c# - 如果 C# 句子中存在该单词,如何屏蔽句子中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42716678/