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

Error processing SSI file

Answers

  1. Arian

    • 2020/9/29

    In WPF this can be uses to check if a string is a valid variable name. But it does not regognize reserved strings like "public".

    // works only in WPF!
    public static bool CheckIfStringIsValidVarName(string stringToCheck)
    {
        if (string.IsNullOrWhiteSpace(stringToCheck))
            return false;
    
        TextBox textBox = new TextBox();
    
        try
        {
            // stringToCheck == ""; // !!! does NOT throw !!!
            // stringToCheck == "Name$"; // throws
            // stringToCheck == "0"; // throws
            // stringToCheck == "name with blank"; // throws
            // stringToCheck == "public"; // does NOT throw
            // stringToCheck == "ValidName";
    
            textBox.Name = stringToCheck;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    
        return true;
    }
    
  2. Gatlin

    • 2017/7/30

    To catch these, you can first check if the string is a keyword, then remove @ from the start of the string, and then check if what's left is a 

  3. Bruno

    • 2018/9/25

    2. There are a couple of special cases around the @character that are easy to forget to check - namely, '@'by itself is not a valid identifier, and neither is "@1foo". To catch these, you can first check if the string is a keyword, then remove @from the start of the string, and then check if what's left is a valid identifier (disallowing @characters).

  4. Toby

    • 2016/10/28

    tf = isvarname( s ) determines if input s is a valid variable name. If s is a valid MATLAB® variable name the isvarname function returns logical 1 ( true ).

  5. Kuqi

    • 2018/2/22

    The longer way, plus it is much slower, is to use reflection to iterate over members of a class/namespace and compare by checking if the reflected member**.ToString()** is the same as the string input, this requires having the assembly loaded beforehand.

    Another way of doing it (a much longer way round it that overcomes the use of regex, by using an already available Antlr scanner/parser) borders on parsing/lexing C# code and then scanning for member names (i.e. variables) and comparing to the string used as an input, for example, input a string called 'fooBar', then specify the source (such as assembly or C# code) and scan it by analyzing looking specifically for declaration of members such as for example

    private int fooBar;
    

    Yes, it is complex but a powerful understanding will arise when you realize what compiler writers are doing and will enhance your knowledge of the C# language to a level where you get quite intimate with the syntax and its peculiarities.

  6. Ricci

    • 2020/2/12

    tf = isvarname(s) determines if input s is a valid variable name. If s is a valid MATLAB ® variable name the isvarname function returns logical 1 (true). Otherwise it returns logical 0 (false). A valid variable name begins with a letter and contains not more than namelengthmax characters. Valid variable names can include letters, digits, and underscores.

  7. Andres

    • 2019/1/6

    Check whether the given string is a valid identifier · It must start with either underscore(_) or any of the characters from the ranges ['a', 'z'] 

  8. Matthew

    • 2021/7/12

    python check if var is string. python test if a var is a string. check if type is string python. python check is variables is strinh. how to check if a var is a string python. check data is string python. python check variable type is string. checking if type is string python. check variable with str python.

  9. Shawn

    • 2021/2/10

    Try this:

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

    • 2019/4/29

    A variable name is a word that consists only of the following: The following are examples of valid variable names: age, gender, x25, 

  11. Vivaan

    • 2019/2/20

    Given a string str, the task is to check if the string is a valid identifier or not. In order to qualify as a valid identifier, the string must satisfy the following conditions: It must start with either underscore(_) or any of the characters from the ranges [‘a’, ‘z’] and [‘A’, ‘Z’]. There must not be any white space in the string.

  12. Mark

    • 2018/3/7

    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, 

  13. Paxton

    • 2015/11/16

    There are a couple of special cases around the @ character that are easy to forget to check - namely, '@' by itself is not a valid identifier, and neither is "@1foo". To catch these, you can first check if the string is a keyword, then remove @ from the start of the string, and then check if what's left is a valid identifier (disallowing @ characters).

    Here I've combined this with a method to parse Unicode escape sequences in identifiers, and hopefully complete C# (5.0) Unicode character checking. To use it, first call TryParseRawIdentifier() to handle keywords, escape sequences, formatting characters (which are removed), and verbatim identifiers. Next, pass the result to IsValidParsedIdentifier() to check if the first and subsequent characters are valid. Note that the strings returned from TryParseRawIdentifier() are equal if and only if the identifiers are considered identical by C#.

    public static class CSharpIdentifiers
    {
        private static HashSet<string> _keywords = new HashSet<string> {
            "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
            "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
            "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
            "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
            "long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
            "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
            "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
            "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
            "virtual", "void", "volatile", "while"
        };
    
        public static IReadOnlyCollection<string> Keywords { get { return _keywords; } }
    
    
        public static bool TryParseRawIdentifier(string str, out string parsed)
        {
            if (string.IsNullOrEmpty(str) || _keywords.Contains(str)) { parsed = null; return false; }
    
            StringBuilder sb = new StringBuilder(str.Length);
    
            int verbatimCharWidth = str[0] == '@' ? 1 : 0;
    
            for (int i = verbatimCharWidth; i < str.Length; ) //Manual increment
            {
                char c = str[i];
    
                if (c == '\\')
                {
                    char next = str[i + 1];
    
                    int charCodeLength;
                    if (next == 'u') charCodeLength = 4;
                    else if (next == 'U') charCodeLength = 8;
                    else { parsed = null; return false; }
                    //No need to check for escaped backslashes or special sequences like \n,
                    //as they not valid identifier characters
    
                    int charCode;
                    if (!TryParseHex(str.Substring(i + 2, charCodeLength), out charCode)) { parsed = null; return false; }
    
                    sb.Append(char.ConvertFromUtf32(charCodeLength)); //Handle characters above 2^16 by converting them to a surrogate pair
                    i += 2 + charCodeLength;
                }
                else if (char.GetUnicodeCategory(str, i) == UnicodeCategory.Format)
                {
                    //Use (string, index) in order to handle surrogate pairs
                    //Skip this character
                    if (char.IsSurrogatePair(str, i)) i += 2;
                    else i += 1;
                }
                else
                {
                    sb.Append(c);
                    i++;
                }
            }
    
            parsed = sb.ToString();
            return true;
        }
    
        private static bool TryParseHex(string str, out int result)
        {
            return int.TryParse(str, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out result);
            //NumberStyles.AllowHexSpecifier forces all characters to be hex digits
        }
    
        public static bool IsValidParsedIdentifier(string str)
        {
            if (string.IsNullOrEmpty(str)) return false;
    
            if (!IsValidParsedIdentifierStart(str, 0)) return false;
    
            int firstCharWidth = char.IsSurrogatePair(str, 0) ? 2 : 1;
    
            for (int i = firstCharWidth; i < str.Length; ) //Manual increment
            {
                if (!IsValidParsedIdentifierPart(str, i)) return false;
                if (char.IsSurrogatePair(str, i)) i += 2;
                else i += 1;
            }
    
            return true;
        }
    
        //(String, index) pairs are used instead of chars in order to support surrogate pairs
        //(Unicode code-points above 2^16 represented using two 16-bit characters)
    
        public static bool IsValidParsedIdentifierStart(string s, int index)
        {
            return s[index] == '_' || char.IsLetter(s, index) || char.GetUnicodeCategory(s, index) == UnicodeCategory.LetterNumber;
        }
    
        public static bool IsValidParsedIdentifierPart(string s, int index)
        {
            if (s[index] == '_' || (s[index] >= '0' && s[index] <= '9') || char.IsLetter(s, index)) return true;
    
            switch (char.GetUnicodeCategory(s, index))
            {
                case UnicodeCategory.LetterNumber: //Eg. Special Roman numeral characters (not covered by IsLetter())
                case UnicodeCategory.DecimalDigitNumber: //Includes decimal digits in other cultures
                case UnicodeCategory.ConnectorPunctuation:
                case UnicodeCategory.NonSpacingMark:
                case UnicodeCategory.SpacingCombiningMark:
                //UnicodeCategory.Format handled in TryParseRawIdentifier()
                    return true;
                default:
                    return false;
            }
        }
    }
    
  14. Ethan

    • 2017/9/25

    Then we make a pattern that consists of a sequence of characters necessary for a valid identifier. And we use this pattern to search whether the string is a valid identifier or not. import re s = input("Enter a string") pattern = r'^[a-zA-Z_]\w*$' if(re.search(pattern,s)): print(" Valid") else: print(" Invalid")

  15. Elliot

    • 2021/3/31

    Valid names of variables. You can define symbolic variables with meaningful names. Note that an ampersand (&) is not part of a variable name; 

  16. Jesse

    • 2019/9/30

    varname = genvarname (str) constructs a string or character vector varname that is similar to or the same as the str input, and can be used as a valid variable name. str can be a string, a string array, a character array, a cell array of character vectors. If str is a string array or cell array of character vectors, genvarname returns a string array or cell array of character vectors in varname.

  17. Fox

    • 2018/10/22
      public static bool IsIdentifier(string text)
      {
         if (string.IsNullOrEmpty(text))
            return false;
         if (!char.IsLetter(text[0]) && text[0] != '_')
            return false;
         for (int ix = 1; ix < text.Length; ++ix)
            if (!char.IsLetterOrDigit(text[ix]) && text[ix] != '_')
               return false;
         return true;
      }
    
  18. Messina

    • 2019/11/6

    Does a class exist to verify that a string contains a valid variable name. I am generating code based on user input and need to verify it.

  19. Brian

    • 2017/4/21

    Check if a string is in a set of valid values. validStrings = [ "wind", "wonder", "when" ]; str = "wind" ; validStr = validatestring (str,validStrings) validStr = "wind". Check if "WON" is in the set of valid values defined by validStrings. The string is a case-insensitive, partial-match to "wonder".

  20. Forest

    • 2021/7/6

    First of all, we check if input starts with a digit or contains a non-word character (anything other than a-z , A-Z , digits and underscore). If 

  21. Vihaan

    • 2019/7/24

    A valid variable name is composed of letters, digits, and underscores ("_"), and the first character must not be a digit. See also: iskeyword, exist, who. : 

  22. Diego

    • 2016/7/19

    is_valid_name: Check if string is valid variable name. In nsgrantham/scriptr: Compose Command Line Programs with Ease.

Comments are closed.

More Posts