猿问

Go : regexp 交换案例

我想在 Go 中使用正则表达式交换案例。我尝试在 Javascript 中使用类似的方法,但我不知道如何让 Go 理解 $ 符号。


func swapcase(str string) string {

    var validID = regexp.MustCompile(`[A-Z]`)

    return validID.ReplaceAllString(str, strings.ToLower(str))


/*

 var validID = regexp.MustCompile(`[a-z]`)

 return validID.ReplaceAllString(str, strings.ToUpper(str))

*/

}

这是我的尝试。它适用于将所有上转换为下,反之亦然,但我想要做的是同时交换每个字母。例如,“你好”--->“你好”


以下是我在 Javascript 中运行完美的代码。


 function SwapCase(str) {


     return str.replace(/([a-z])|([A-Z])/g,

        function($0, $1, $2) {

            return ($1) ? $0.toUpperCase() : $0.toLowerCase();

        })

 }


小唯快跑啊
浏览 164回答 1
1回答

慕侠2389804

你不能(我认为)用正则表达式来做到这一点,但使用strings.Map.package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func swapCase(r rune) rune {&nbsp; &nbsp; switch {&nbsp; &nbsp; case 'a' <= r && r <= 'z':&nbsp; &nbsp; &nbsp; &nbsp; return r - 'a' + 'A'&nbsp; &nbsp; case 'A' <= r && r <= 'Z':&nbsp; &nbsp; &nbsp; &nbsp; return r - 'A' + 'a'&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; return r&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; s := "helLo WoRlD"&nbsp; &nbsp; fmt.Println(strings.Map(swapCase, s))}
随时随地看视频慕课网APP

相关分类

Go
我要回答