douhuan1648
2016-12-23 10:20
浏览 1.1k
已采纳

转义字符串特殊字符,用于golang正则表达式

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?

图片转代码服务由CSDN问答提供 功能建议

我有一个这样的字符数组:

 字符 := [] string {“。”,“-”,“(”,“)”} 
   
 
 

当我以常规方式加入它们时( strings.Join(chars,“”))并将其传递给 regexp.MustCompile ,它的恐慌是:

  panic:regexp:  Compile(`[.-()]`):解析正则表达式时出错:无效的字符类范围:`.-(`
   
 
 

如何对字符串特殊字符进行转义 可以在golang regexp中用作字符而不是regexp运算符?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duandu9260 2016-12-23 10:23
    已采纳

    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.

    点赞 打赏 评论

相关推荐 更多相似问题