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?
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\\\""
Or
str := `I have Hello \"World\"`
A working demonstration can be found here.