Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang regex replace does nothing

Tags:

regex

go

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
}
like image 628
karka91 Avatar asked Dec 02 '12 19:12

karka91


1 Answers

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
like image 78
zzzz Avatar answered Sep 20 '22 07:09

zzzz