Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,025 questions

51,979 answers

573 users

How to convert a string to PascalCase using RegEx in Go

1 Answer

0 votes
package main

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

func toPascalCase(input string) string {
        // 1. Handle camelCase by inserting spaces
        re := regexp.MustCompile("([a-z])([A-Z])")
        input = re.ReplaceAllString(input, "$1 $2")

        // 2. Replace non-breaking spaces with regular spaces
        input = strings.ReplaceAll(input, "\u00A0", " ")

        // 3. Split into words using spaces and underscores as delimiters
        words := strings.FieldsFunc(strings.ToLower(input), func(r rune) bool {
                return unicode.IsSpace(r) || r == '_'
        })

        var result string
        for _, word := range words {
                if len(word) > 0 {
                        // 4. Capitalize the first letter of each word
                        runes := []rune(word)
                        runes[0] = unicode.ToUpper(runes[0])
                        result += string(runes)
                }
        }
        return result
}

func main() {
        fmt.Println(toPascalCase("get file content"))
        fmt.Println(toPascalCase("get_file_content"))
        fmt.Println(toPascalCase("get______file___content"))
        fmt.Println(toPascalCase("get______file____\u00A0 content"))
        fmt.Println(toPascalCase("GET FILE CONTENT"))
        fmt.Println(toPascalCase("get\u00A0 \u00A0 file\u00A0 \u00A0 \u00A0 content"))
        fmt.Println(toPascalCase("getFileContent"))
        fmt.Println(toPascalCase("  get file content")) 
        fmt.Println(toPascalCase("get file content  ")) 
}



/*
run:

GetFileContent
GetFileContent
GetFileContent
GetFileContent
GetFileContent
GetFileContent
GetFileContent
GetFileContent
GetFileContent

*/

 



answered Feb 23, 2025 by avibootz

Related questions

1 answer 87 views
2 answers 99 views
1 answer 81 views
1 answer 89 views
1 answer 79 views
...