I'm not convinced that regular expressions are the best approach here, but these should work.
ReplaceWithX
replaces every single character (specified by .
) with an x
.
ReplaceWithXLeave4
replaces all but the last four characters with an x
. It does this by matching any single character (.
) while using a zero-width negative lookahead assertion to throw out this match for the last four characters.
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");
}
}
}
And for completeness, below is what it looks like when not using regular expressions. This approach is probably quite a bit faster than the regex approach, even though you might not ever see the perf difference when just doing it once or twice like these examples are. In other words, if you're doing this on a server with lots of requests, avoid regex since it's only marginally easier to read.
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();
}
}
}