ITPub博客

首页 > 应用开发 > > 求 .NET Core 中判断字符串

求 .NET Core 中判断字符串

作者:chinarocky 时间:2019-08-27 14:20:09 0 删除 编辑

求 .NET Core 中判断字符串是否由字母、数字、连字符、下划线组成的最快方法



判断规则:字符串中只能包含字母、数字、连字符、下划线,字符串最少1个字符,最多150字符。

使用正则表达式判断的代码以及执行速度如下,求比正则表达更快的方法。

class Program
{
    private const int loops = 10000;
    private static readonly Regex _regex = new Regex(@"^[-_a-zA-Z0-9]{1,150}$", RegexOptions.Compiled);

    static void Main(string[] args)
    {
        Stopwatch sw = Stopwatch.StartNew();

        for (var i = 0; i < loops; i++)
        {
            var str = Guid.NewGuid().ToString();
            _regex.IsMatch(str);
        }

        sw.Stop();
        Console.WriteLine($"Elapsed Ticks: {(int)(sw.ElapsedTicks / loops)}");
    }
}

使用正则表达式,执行1万次的平均耗时在 45 ticks 左右。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4547/viewspace-3147014/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-10

  • 博文量
    213
  • 访问量
    1690