正则表达式替换可变长度字符串中的所有字符

Kam*_*mal 2 c# regex vb.net string

使用VB或C#,我从数据库中获取一个可变长度的字符串.此信息是仅某些用户才能看到的敏感信息.

我有两种情况会使用相同的逻辑(我认为).

方案1:用x替换所有字符

场景2:用最后4个字符替换除x之外的所有字符(假设长度> 4 - 正在进行此检查).

我认为这最容易使用Regex.Replace(输入,模式,替换字符串).与使用子串进行大量字符串处理并强制使用'x'的长度相反.

但似乎Regex永远是我的氪星石.

任何正则表达式大师的帮助将不胜感激.或者,欢迎更好的解决方案.

Chr*_*ich 5

我不相信正则表达式是最好的方法,但这些应该有效.

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)