Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape string special characters for use in golang regexp

Tags:

string

regex

go

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?

like image 945
Dariush Abbasi Avatar asked Dec 23 '16 10:12

Dariush Abbasi


People also ask

How do you escape special characters in Golang?

To insert escape characters, use interpreted string literals delimited by double quotes. The escape character \t denotes a horizontal tab and \n is a line feed or newline.

How do you escape a string in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

What is ?: In regex?

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.


1 Answers

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.

like image 185
Wiktor Stribiżew Avatar answered Oct 13 '22 04:10

Wiktor Stribiżew