2013-09-30 21:37



In go, how do I detect \ back slash character itself?

 str := "I have Hello \"World\""
 var validID = regexp.MustCompile(`[.!?]`)

this is how I detect . ! ? characters but

 var validID = regexp.MustCompile(`[\]`)

does not detect the backslash in the string.

How do I denote backslash in go regular expression?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doujing5150 doujing5150 8年前

    You'll need to escape it, even in a character class; otherwise it will think you're trying to escape the ]:

    var validID = regexp.MustCompile(`[\\]`)

    But for that matter, you can just get rid of the character class entirely:

    var validID = regexp.MustCompile(`\\`)

    Also note that the string "I have Hello \"World\"" does not actually contain any backlashes. \" is an escape sequence a double quote. If you want to create a string with backslashes use:

    str := "I have Hello \\\"World\\\""


    str := `I have Hello \"World\"`

    A working demonstration can be found here.

    点赞 评论 复制链接分享