我不相信正则表达式是最好的方法,但这些应该有效.
ReplaceWithX用一个替换每个单个字符(由...指定.)x.
ReplaceWithXLeave4用一个替换除了最后四个字符以外的所有字符x.它通过匹配任何单个字符(.),同时使用零宽度负前瞻断言来为最后四个字符抛出此匹配来完成此操作.
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,下面是不使用正则表达式时的样子.这种方法可能比正则表达式方法快得多,即使你只是像这些例子那样只做一次或两次时可能看不到性能差异.换句话说,如果您在具有大量请求的服务器上执行此操作,请避免使用正则表达式,因为它只是稍微容易阅读.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)