Regex to Match Programming Variable Names

Validate programming variable names with this regex. Matches identifiers starting with a letter, underscore, or dollar sign. Free tool.

Regular Expression

/^[a-zA-Z_$][a-zA-Z0-9_$]*$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
[a-zA-Z_$]Character class — matches any one of: a-zA-Z_$
[a-zA-Z0-9_$]Character class — matches any one of: a-zA-Z0-9_$
*Matches the preceding element zero or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates variable names (identifiers) as used in most programming languages including JavaScript, Python, Java, and C. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string.

[a-zA-Z_$] — A character class matching the first character of the variable name. It allows uppercase letters (A-Z), lowercase letters (a-z), underscore (_), and dollar sign ($). Most programming languages require identifiers to start with a letter, underscore, or (in JavaScript) a dollar sign. Digits are not allowed as the first character to prevent ambiguity with numeric literals.

[a-zA-Z0-9_$]* — A character class matching the remaining characters. It allows the same characters as the first class plus digits (0-9). The * quantifier allows zero or more characters, so single-character names like 'x' or '_' are valid.

$ — Anchors the match at the end of the string.

This pattern covers the common identifier rules shared by most C-family languages. It matches names like 'myVariable', '_privateField', '$jQueryElement', 'MAX_SIZE', and 'x1'. It does not match names starting with digits like '2nd' or names containing spaces or special characters. Note that this pattern does not check for reserved words (keywords). A variable name might match this regex but still be invalid if it conflicts with a language keyword like 'class' or 'return'. Keyword checking requires a separate validation step.

Example Test Strings

InputExpected
myVariableMatch
_privateFieldMatch
2ndValueNo Match
$elementMatch
my-variableNo Match

Try It — Interactive Tester

//
gimsuy
No matches found.
Pattern: 26 charsFlags: noneMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →