Using regex in golang, I'd like to replace all non-alphanumeric characters of any languages with -
, in order to make pretty urls:
Here is one of many regex that I've tried:
package main
import (
"fmt"
"regexp"
)
const sample = `سلام دنیا hello world 1 %^&`
func main() {
var re = regexp.MustCompile(`~[\p{L}0-9\s]+`)
s := re.ReplaceAllString(sample, `-`)
fmt.Println(s)
}
The output should be: سلام-دنیا-hello-world-1
But it does not work. How can I fix it?
Why do you use ~
at the beginning? If you want to se negated set, use ^
inside of the brackets: [^...]
. Also if you want to replace whitespaces, don't include \s
in the negated set definition:
[^\p{L}0-9]+