scott
scott

Reputation: 1637

golang selective conversion of string to lower case

I am working with an ldap object where I am retrieving some entries from Activedirectory. The results are in such a way that the realm is returned in uppercase, like CN=bob,DC=example,DC=com instead of cn=bob,dc=example,dc=com. Is there a way to selectively convert the CN and DC substrings to lowercase? Sofar, I was using strings.split multiple times (using "," first and then iterating again using "=") to get to the point where I can get CN, DC, etc. into a list, and then using strings.ToLower on them. Is there a better and smarter way to get this done, possibly using regex so that I can possibly avoid two iterations?

Upvotes: 3

Views: 2489

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Here is a regex way to make all uppercase chunks of text followed with a = tp lower case:

package main

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

func main() {
        input := "CN=bob,DC=example,DC=com"
        r := regexp.MustCompile(`[A-Z]+=`)
        fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string {
                return strings.ToLower(m)
        }))
}

See the Playground demo

The regex - [A-Z]+= - matches 1 or more uppercase ASCII letters and a = after them. Then, inside the ReplaceAllStringFunc, we can use an "anonymous function" to return a modified match value.

Upvotes: 6

Uvelichitel
Uvelichitel

Reputation: 8490

Doesn't

strings.Replace(results, "CN", "cn", -1)

can help? https://golang.org/pkg/strings/#Replace

Upvotes: 0

Related Questions