I want to swap cases using regexp in Go. I tried to use the similar method in Javascript but I can't figure out how to make Go understand $ sign.
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))
*/
}
This was my try. It works for converting all upper to lower, and vice versa, but what I want to do is to swap every letter at the same time. For example, "Hello" ---> "hELLO"
And the following is my code in Javascript that works perfect.
function SwapCase(str) {
return str.replace(/([a-z])|([A-Z])/g,
function($0, $1, $2) {
return ($1) ? $0.toUpperCase() : $0.toLowerCase();
})
}
You can't (I think) do this with a regexp, but it's straightforward with strings.Map
.
package main
import (
"fmt"
"strings"
)
func swapCase(r rune) rune {
switch {
case 'a' <= r && r <= 'z':
return r - 'a' + 'A'
case 'A' <= r && r <= 'Z':
return r - 'A' + 'a'
default:
return r
}
}
func main() {
s := "helLo WoRlD"
fmt.Println(strings.Map(swapCase, s))
}