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

转义字符串特殊字符,用于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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划