Package regexp

Table of Contents

Convert camelCase or PascalCase to snake_case howto

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func ToSnake(s0 string) string {
    p1 := regexp.MustCompile(`(.)([A-Z][a-z]+)`)
    s1 := p1.ReplaceAllString(s0, `${1}_${2}`)
    p2 := regexp.MustCompile(`([a-z0-9])([A-Z])`)
    s2 := p2.ReplaceAllString(s1, "${1}_${2}")
    return strings.ToLower(s2)
}

func main() {
    fmt.Println(ToSnake("PascalCase"))
    fmt.Println(ToSnake("PascalPascalCase"))
    fmt.Println(ToSnake("Pascal2Pascal2Case"))
    fmt.Println(ToSnake("getHTTPResponseCode"))
    fmt.Println(ToSnake("get2HTTPResponseCode"))
    fmt.Println(ToSnake("HTTPResponseCode"))
    fmt.Println(ToSnake("HTTPResponseCodeXYZ"))
}
pascal_case
pascal_pascal_case
pascal2_pascal2_case
get_http_response_code
get2_http_response_code
http_response_code
http_response_code_xyz