karka91
karka91

Reputation: 733

Golang regex replace does nothing

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
}

Upvotes: 19

Views: 15065

Answers (1)

zzzz
zzzz

Reputation: 91253

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

Upvotes: 34

Related Questions