可以使用正则表达式来判断类名开头是否只能是大小写字母和下划线:

using System.Text.RegularExpressions;

public static bool IsValidClassName(string className)
{
    // ^ 表示匹配开头,[A-Za-z_] 表示大小写字母和下划线,\w* 表示匹配任意个字母、数字或下划线
    string pattern = "^[A-Za-z_]\w*";
    Regex regex = new Regex(pattern);
    return regex.IsMatch(className);
}

使用示例:

string className = '_MyClass';
bool isValid = IsValidClassName(className); // true

className = '123MyClass';
isValid = IsValidClassName(className); // false

className = 'my_Class';
isValid = IsValidClassName(className); // true
C# 正则表达式验证类名开头是否为字母或下划线

原文地址: https://www.cveoy.top/t/topic/lrU4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录