Given a string, determine if it's a valid identifier.
Here is the syntax for valid identifiers:
- Each identifier must have at least one character.
- The first character must be picked from: alpha, underscore, or dollar sign. The first character can not be a digit.
- The rest of the characters (besides the first) can be from: alpha, digit, underscore, or dollar sign. In other words, it can be any valid identifier character.
Examples of valid identifiers:
- i
- wo_rd
- b2h
Examples of invalid identifiers:
- 1i
- wo rd
- !b2h
using System;using System.Text.RegularExpressions;public class IdentifierChecker { public static bool IsValid(string input) { string pattern = @"^[A-Za-z_$][\w_$]+$"; Regex regex = new Regex(pattern); return regex.IsMatch(input); }}
^...$开头和结尾
[A-Za-z_$] 第一个字符的可选范围 [\w_$]后续字符的可选范围 + 一个或多个重复