8

I have an array of characters like this :

chars := []string{".", "-", "(", ")"}

When I join them in regular way (strings.Join(chars, "")) and pass it to regexp.MustCompile, Its panic :

panic: regexp: Compile(`[.-()]`): error parsing regexp: invalid character class range: `.-(`

How can I scape string special characters for use in golang regexp as a character not regexp operator?

2 Answers 2

11

You must put the - item at the start/end of the array so that - appears either at the start - [-.()] - or end - [.()-] - of the character class.

Or escape the - in the chars array: "\\-".

NOTE: That is not the only caveat, the ^ and ] must also be escaped, or placed in a specific location in the character class. The \ must be escaped always.

See a Go demo:

package main

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

func main() {
    chars := []string{"]", "^", "\\\\", "[", ".", "(", ")", "-"}
    r := strings.Join(chars, "")
    s := "[Some]-\\(string)^."
    re := regexp.MustCompile("[" + r + "]+")
    s = re.ReplaceAllString(s, "")
    fmt.Println(s)
}

Output: Somestring

Note that the ^ must not be the first item, ] must be at the start and - at the end.

Sign up to request clarification or add additional context in comments.

Comments

3

Now there is an even better way:

regexp.MustCompile( regexp.QuoteMeta(strings.Join(chars, "")) )

regexp.QuoteMeta() will create a regular expression that matches the string provided exactly (i.e. it will escape all the regex meta-characters).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.