Regex目录名称验证

本文关键字:验证 Regex | 更新日期: 2023-09-27 18:24:32

我想检查文本框是否有有效的目录名。因为我将用这个文本框值创建一个目录。

另外,该值必须至少有3个字符,并且不能超过20个字符。

我该怎么做?

Regex目录名称验证

Path.GetInvalidPathChars是您可以找出哪些字符无效的地方。与其使用regex,我建议您使用Path.GetFullPath,因为这将为您验证路径:它总是比您尝试滚动的任何东西都做得更好,并且随着规则的变化,它将保持最新。

至于它的长度,请使用Path类的方法来获取要检查的路径的组件。

不需要RegEx,这是一种浪费。

public bool ValidName(string dirName)
{
    char[] reserved = Path.GetInvalidFileNameChars();
    if (dirName.Length < 3)
         return false;
    if (dirName > 20)
         return false;
    foreach (char c in reserved)
    {
         if (dirName.Contains(c))
             return false;
    }
    return true;
}

RegEx不是特别有效,在这里也不是真正必要的。只需检查边界,然后确保字符串不包含任何保留字符,一旦发现错误就会返回false。

简易

这是您应该使用的regex。

^[0-9A-Za-Z_-]{3,20}$
"^"means starts with the characters defined in [] brackets
"[]" represents list of allowed characters
"0-9" represents that numbers from 0-9 can be used
"A-Z" uppercase letters from A to Z
"a-z" lowercase letters from a to z
"_" underscore
"-" dash
"{}" represents limitations
"{3,20}" - min 3 characters max 20
"$" ends with the characters defined in []

若不使用^$,它将搜索字符串中这些字母的组合,所以字符串可以是30个字符,它将是有效的。

我希望这能帮助