Golang正则表达式替换没有任何效果

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

Golang regex replace does nothing

问题

我想用破折号替换任何非字母数字字符序列。我写的一部分代码如下。然而它不起作用,我完全不知道为什么。有人能解释一下为什么这段代码的行为不像我期望的那样,并且正确的实现方法是什么吗?

package main

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

func main() {
    reg, _ := regexp.Compile("/[^A-Za-z0-9]+/")
    safe := reg.ReplaceAllString("a*-+fe5v9034,j*.AE6", "-")
    safe = strings.ToLower(strings.Trim(safe, "-"))
    fmt.Println(safe)  // 输出:a*-+fe5v9034,j*.ae6
}
英文:

I want to replace any non-alphanumeric character sequences with a dash. A snippet of what I wrote is below. However it does not work and I'm completely clueless why. Could anyone explain me why the snippet behaves not like I expect it to and what would be the correct way to accomplish this?

package main

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

func main() {
	reg, _ := regexp.Compile("/[^A-Za-z0-9]+/")
	safe := reg.ReplaceAllString("a*-+fe5v9034,j*.AE6", "-")
	safe = strings.ToLower(strings.Trim(safe, "-"))
	fmt.Println(safe)  // Output: a*-+fe5v9034,j*.ae6
}

答案1

得分: 33

The forward slashes are not matched by your string.

package main

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

func main() {
        reg, err := regexp.Compile("[^A-Za-z0-9]+")
        if err != nil {
                log.Fatal(err)
        }

        safe := reg.ReplaceAllString("a*-+fe5v9034,j*.AE6", "-")
        safe = strings.ToLower(strings.Trim(safe, "-"))
        fmt.Println(safe)	// Output: a*-+fe5v9034,j*.ae6
}

(Also here)

Output

a-fe5v9034-j-ae6
英文:

The forward slashes are not matched by your string.

package main

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

func main() {
        reg, err := regexp.Compile("[^A-Za-z0-9]+")
        if err != nil {
                log.Fatal(err)
        }

        safe := reg.ReplaceAllString("a*-+fe5v9034,j*.AE6", "-")
        safe = strings.ToLower(strings.Trim(safe, "-"))
        fmt.Println(safe)	// Output: a*-+fe5v9034,j*.ae6
}

(Also here)

Output

a-fe5v9034-j-ae6

huangapple
  • 本文由 发表于 2012年12月3日 03:29:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/13672913.html
匿名

发表评论

匿名网友

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

确定