Go : regexp to swap cases

huangapple go评论93阅读模式
英文:

Go : regexp to swap cases

问题

我想在Go语言中使用正则表达式来交换大小写。我尝试使用类似于JavaScript的方法,但我无法让Go理解美元符号。

func swapcase(str string) string {
    var validID = regexp.MustCompile(`[A-Z]`)
    return validID.ReplaceAllStringFunc(str, func(match string) string {
        if match == strings.ToUpper(match) {
            return strings.ToLower(match)
        } else {
            return strings.ToUpper(match)
        }
    })
}

这是我的尝试。它可以将所有大写字母转换为小写字母,反之亦然,但我想要的是同时交换每个字母的大小写。例如,"Hello" ---> "hELLO"

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

function SwapCase(str) {
    return str.replace(/([a-z])|([A-Z])/g, function($0, $1, $2) {
        return ($1) ? $0.toUpperCase() : $0.toLowerCase();
    });
}
英文:

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();
     	})
 }

答案1

得分: 1

你可以使用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))
}

这段代码使用了strings.Map函数来实现大小写互换。swapCase函数用于将小写字母转换为大写字母,将大写字母转换为小写字母,其他字符保持不变。在main函数中,我们定义了一个字符串s,然后使用strings.Map函数将s中的每个字符都应用swapCase函数进行转换,并打印结果。

英文:

You can't (I think) do this with a regexp, but it's straightforward with strings.Map.

package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func swapCase(r rune) rune {
	switch {
	case &#39;a&#39; &lt;= r &amp;&amp; r &lt;= &#39;z&#39;:
		return r - &#39;a&#39; + &#39;A&#39;
	case &#39;A&#39; &lt;= r &amp;&amp; r &lt;= &#39;Z&#39;:
		return r - &#39;A&#39; + &#39;a&#39;
	default:
		return r
	}
}

func main() {
	s := &quot;helLo WoRlD&quot;
	fmt.Println(strings.Map(swapCase, s))
}

huangapple
  • 本文由 发表于 2013年9月28日 16:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/19064937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定