英文:
Go regexp to detect backslash character
问题
在Go语言中,要检测反斜杠字符本身,你可以使用双反斜杠来表示反斜杠。以下是你可以尝试的代码:
str := "I have Hello \\\"World\\\""
var validID = regexp.MustCompile(`[.!?]`)
var validBackslash = regexp.MustCompile(`\\\\`)
在正则表达式中,\\
表示一个反斜杠字符。因为反斜杠在正则表达式中有特殊含义,所以需要使用两个反斜杠来表示一个反斜杠字符本身。
英文:
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?
答案1
得分: 3
你需要对它进行转义,即使在字符类中也是如此;否则它会认为你试图转义]
:
var validID = regexp.MustCompile(`[\\]`)
但是,你也可以完全去掉字符类:
var validID = regexp.MustCompile(`\\`)
还要注意,字符串"I have Hello \"World\""
实际上不包含任何反斜杠。\\"
是一个转义序列,表示双引号。如果你想创建一个包含反斜杠的字符串,请使用:
str := "I have Hello \\\"World\\\""
或者
str := `I have Hello \"World\"`
可以在这里找到一个可工作的演示。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论