regex 允许下划线和字母数字的正则表达式代码在c#中不起作用

yyhrrdl8  于 2023-01-14  发布在  C#
关注(0)|答案(1)|浏览(141)

我创建了一个函数,以允许字母数字与下划线,我尝试了我的组合,许多正则表达式模式,但没有一个是工作,我无法找出什么是错的,从我的身边。我也写了问题,我面临的每一个正则表达式的评论。请找到我的代码如下:-

public static int ValidateName()
{
    string FileName="Test_3678";//Allowed
    //string FileName="Test.Request_3678";//Not Allowed
    int i = 0;

    string pattern = @"^[a-zA-Z][a-zA-Z0-9_.]+\s?$";//Allows dot in the name, when I remove dot it doesn't allow any special character including underscore
    //string pattern = @"^[a-zA-Z0-9_]+$";//Not Allowing special characters and underscore
    //string pattern = @"^[a-zA-Z0-9_]*";//Allowing special characters and underscore
    //string pattern = "@^[a-zA-Z0-9_]*$";//Not Allowing special characters and underscore

    Regex regex = new Regex(pattern);
    bool flagFileName = false;
    flagFileName = regex.IsMatch(FileName.Trim());
    if (!flagFileName )
    {
        i = 0;
    }
    else
    {
        i = 1;
    }
    return i;
}

谢谢你,

zpgglvta

zpgglvta1#

使用正则表达式^[a-zA-Z0-9_]*$,不要从方法返回int,这是不必要的。您可以返回bool

相关问题