-4

如何在 C# 中使用 RegEx 将整个文本替换为 XXX?它将替换等于字符串长度的 X 的数量。

例如原始文本是Apple替换为XXXXX

板球XXXXXX

你好XX

优秀XXXXXXXXXXXX

String MyText = "Apple";
//For following line i have to written regexp to achieve 
String Output = "XXXXX"; //Apple will replace with 5 times X because Apple.length = 5
4

3 回答 3

3

没有正则表达式:

string s = "for example original text is Apple replace";

var replaceWord = "Apple";
var s2 = s.Replace(replaceWord , new String('X', replaceWord.Length));

创建一个由 'X' 字符组成的new String('X', replaceWord.Length)字符串,其长度与 相同replaceWord

于 2013-03-21T09:27:33.377 回答
2

您不需要 Regex 或 Replace 方法,而是可以使用Enumerable.Repeat<TResult> Method创建一个字符数组X (原始字符串长度),然后将其传递给字符串构造函数。

string originalStr = "Apple";    
string str = new string(Enumerable.Repeat<char>('X',originalStr.Length)
                                      .ToArray());

str将举行:str = "XXXXX"

编辑: 由于您需要与单个字符的原始字符串长度相同的字符串,您可以使用: String Constructor (Char, Int32),这是一个更好的选择。

string str3 = new string('X', originalStr.Length);
于 2013-03-21T09:25:30.970 回答
2

为什么不简单地使用:

String.Replace(word, new String('X', word.Length));
于 2013-03-21T09:26:32.333 回答