英文:
golang selective conversion of string to lower case
问题
我正在使用一个ldap对象,从Active Directory中检索一些条目。结果以大写形式返回,例如CN=bob,DC=example,DC=com
,而不是cn=bob,dc=example,dc=com
。有没有办法选择性地将CN
和DC
子字符串转换为小写?到目前为止,我多次使用strings.split
(首先使用",",然后再使用"="进行迭代)来获取CN、DC等内容,并对它们使用strings.ToLower
。有没有更好、更智能的方法来完成这个任务,可能使用正则表达式,以避免两次迭代?
英文:
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?
答案1
得分: 6
这是一个使用正则表达式的方法,将所有大写的文本块后面的=
转换为小写:
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)
}))
}
可以在Playground演示中查看示例。
正则表达式[A-Z]+=
匹配一个或多个大写ASCII字母,后面跟着一个=
。然后,在ReplaceAllStringFunc
中,我们可以使用一个“匿名函数”来返回修改后的匹配值。
英文:
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.
答案2
得分: 0
不需要翻译的部分:strings.Replace(results, "CN", "cn", -1)
和链接https://golang.org/pkg/strings/#Replace
。
翻译部分:strings.Replace(results, "CN", "cn", -1)
可以帮助吗?
英文:
Doesn't
strings.Replace(results, "CN", "cn", -1)
can help? https://golang.org/pkg/strings/#Replace
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论