Escaping an apostrophe in golang

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

Escaping an apostrophe in golang

问题

在Golang中,你可以通过在字符串中使用双引号来转义撇号。要将字符串中的撇号转义为\',你可以使用以下代码:

s := "I\\'ve this book"

这样,字符串s将被赋值为I\'ve this book。通过在撇号前添加一个反斜杠,你可以实现撇号的转义。希望能帮到你!

英文:

How can I escape an apostrophe in golang?
I have a string

s = "I've this book"

and I want to make it

s = "I\'ve this book"

How to achieve this?
Thanks in advance.

答案1

得分: 7

转义字符只在一个字符有两种或更多种解释的情况下才是必要的。你字符串中的撇号只能被解释为撇号,因此不需要转义。这可能是为什么你看到错误消息 unknown escape sequence: ' 的原因。

如果你需要转义撇号,因为它被插入到数据库中,首先考虑使用库函数进行转义或直接插入数据。在过去的几十年中,正确的转义一直是许多安全问题的罪魁祸首。你几乎肯定会做错

话虽如此,你需要转义 \ 来实现你想要的效果(点击播放):

fmt.Println("\\'") # 输出 \'

由于你正在使用cassandra,你可以使用像 gocql 这样的包来提供参数化查询:

session.Query(`INSERT INTO sometable (text) VALUES (?)`, "'escaping'").Exec();
英文:

Escaping a character is only necessary if it can be interpreted in two or more ways. The apostrophe in your string can only be interpreted as an apostrophe, escaping is therefore not necessary as such. This is probably why you see the error message unknown escape sequence: '.

If you need to escape the apostrophe because it is inserted into a database, first consider using library functions for escaping or inserting data directly. Correct escaping has been the culprit of many security problems in the last decades. You will almost certainly do it wrong.

Having said that, you have to escape \ to do what you want (click to play):

fmt.Println("\\'") # outputs \'

As you're using cassandra, you can use packages like gocql which provide you with parametrized queries:

session.Query(`INSERT INTO sometable (text) VALUES (?)`, "'escaping'").Exec();

huangapple
  • 本文由 发表于 2014年4月15日 07:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/23072047.html
匿名

发表评论

匿名网友

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

确定