Regex to Match snake_case Strings

Validate snake_case identifiers with lowercase letters, digits, and underscores. No leading or trailing underscores or consecutive underscores. Free regex tester.

Regular Expression

/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
[a-z]Character class — matches any one of: a-z
[a-z0-9]Character class — matches any one of: a-z0-9
*Matches the preceding element zero or more times (greedy)
(?:Start of non-capturing group
_Matches the literal character '_'
[a-z0-9]Character class — matches any one of: a-z0-9
+Matches the preceding element one or more times (greedy)
)End of group
*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 strings written in snake_case notation, a naming convention widely used in Python, Ruby, and database column names. Here is the token-by-token breakdown:

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

[a-z] — Matches a single lowercase letter as the first character. Snake case identifiers must start with a letter, not a digit or underscore.

[a-z0-9]* — Matches zero or more lowercase letters or digits for the remainder of the first word segment.

(?:_[a-z0-9]+)* — A non-capturing group that matches zero or more underscore-separated word segments. Each segment consists of a single underscore followed by one or more lowercase letters or digits. This structure prevents consecutive underscores (like my__var), leading underscores, and trailing underscores.

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

No flags are used because case sensitivity is important; snake_case requires all letters to be lowercase.

Snake case is the standard naming convention in Python for variable names, function names, and module names according to PEP 8. It is also commonly used for database column names, JSON API field names in Ruby on Rails, and configuration file keys. Examples include user_name, get_total_count, first_name_last, and api_v2_endpoint.

This pattern enforces clean snake_case formatting without allowing the double-underscore dunder convention used in Python for special methods. For those, a separate pattern would be needed.

Example Test Strings

InputExpected
snake_caseMatch
my_variable_nameMatch
camelCaseNo Match
_leadingNo Match
has__doubleNo Match
simpleMatch

Try It — Interactive Tester

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

Ctrl+Shift+C to copy regex

Customize this pattern →