使用 VB 或 C#,我从数据库中获取可变长度的字符串。此信息是敏感信息,只有某些用户才能看到。
我有两个案例将使用相同的逻辑(我认为)。
场景1:将所有字符替换为x
场景 2:将除最后 4 个字符之外的所有字符替换为 x(假设长度 > 4 - 正在进行此检查)。
我认为使用 Regex.Replace(input,pattern,replacestring) 是最简单的。与使用子字符串进行大量字符串处理并强制长度为“x”相反。
但看来 Regex 永远是我的克星。
如果来自正则表达式专家的任何帮助,我们将不胜感激。或者,欢迎更好的解决方案。
最佳答案
我不相信正则表达式是最好的方法,但这些应该可行。
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();
}
}
}
关于c# - 正则表达式替换可变长度字符串中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3870425/