我不相信正则表达式是这里最好的方法,但这些应该可以工作。
ReplaceWithX 将每个字符(由. 指定)替换为x。
ReplaceWithXLeave4 用x 替换除了最后四个字符之外的所有字符。它通过匹配任何单个字符 (.) 来实现这一点,同时使用 zero-width negative lookahead assertion 来排除最后四个字符的匹配。
using System;
using System.Text.RegularExpressions;
namespace ReplaceRegex
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ReplaceWithX("12345678"));
Console.WriteLine(ReplaceWithXLeave4("12345678"));
}
static string ReplaceWithX(string input)
{
return Regex.Replace(input, ".", "x");
}
static string ReplaceWithXLeave4(string input)
{
return Regex.Replace(input, ".(?!.{0,3}$)", "x");
}
}
}
为了完整起见,下面是不使用正则表达式时的样子。这种方法可能比正则表达式方法快很多,即使像这些示例一样只执行一次或两次时您可能永远看不到性能差异。换句话说,如果您在有大量请求的服务器上执行此操作,请避免使用正则表达式,因为它只是稍微容易阅读。
using System;
using System.Text;
namespace ReplaceNoRegex
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ReplaceWithX("12345678"));
Console.WriteLine(ReplaceWithXLeave4("12345678"));
}
static string ReplaceWithX(string input)
{
return Repeat('x', input.Length);
}
static string ReplaceWithXLeave4(string input)
{
if (input.Length <= 4)
return input;
return Repeat('x', input.Length - 4)
+ input.Substring(input.Length - 4);
}
static string Repeat(char c, int count)
{
StringBuilder repeat = new StringBuilder(count);
for (int i = 0; i < count; ++i)
repeat.Append(c);
return repeat.ToString();
}
}
}