How to determine if a string is a valid variable name?

后端 未结 5 422
执笔经年
执笔经年 2020-12-15 03:43

I\'m looking for a quick way (in C#) to determine if a string is a valid variable name. My first intuition is to whip up some regex to do it, but I\'m wondering if there\'s

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 04:33

    Try this:

    // using System.CodeDom.Compiler;
    CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
    if (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) {
          // Valid
    } else {
          // Not valid
    }
    

提交回复
热议问题