Skip to main content
hank-builds.com

Camel to Snake Case regex

Matches camelCase boundaries. Replace with $1_$2 and lowercase.

/([a-z])([A-Z])/g

What it matches

The boundary inside camelCase: a lowercase letter immediately followed by an uppercase one. Both are captured, which is what makes the $1_$2 replacement work: it puts the two letters back with an underscore between them, and a lowercasing pass afterwards finishes the conversion.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

Group [a-z] Group [A-Z]

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
[a-z]Match one of: Literal "a"–Literal "z"
[A-Z]Match one of: Literal "A"–Literal "Z"

Test cases

Matches

  • myVariableName
  • getSomeValue
  • aB

Does not match

  • lowercase
  • UPPERCASE
  • snake_case

Caveats

Consecutive capitals defeat it. HTMLParser has no lowercase-then-uppercase boundary before HTML, so it becomes h_t_m_l_parser after lowercasing rather than html_parser. Digit boundaries are ignored too, so parseUTF8String needs a second pattern.

More text processing patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.