Go regexp to detect backslash character

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年10月1日 05:37:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/19104311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定