从字符串中删除反斜杠 [英] Remove backslashes from character string

查看:545
本文介绍了从字符串中删除反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从txt文件中读取文本,并将内容传递给SQL. SQL文本包含双引号,并引起问题.我想删除下面字符串中的"\",以便将其发送到SQL

I am reading text in from a txt file and pass the contents to SQL. The SQL text contains double quotes and is causing problems. I would like to remove the "\" in the string below so I can send it to SQL

  test<- "select case when \"est\"  dsaf"
  test<-  cat(test, sep="")
  class(test)

返回一个UNQUOTED空对象

returns an UNQUOTED null object

> test<- "select case when \"est\"  dsaf"
>   test<-  cat(test, sep="")
select case when "est"  dsaf
>   class(test)
[1] "NULL"

当我将未加引号的字符串传递给SQL时,会出现此错误:

When I pass the unquoted string to SQL I get this error:

Error in odbcQuery(channel, query, rows_at_time) : 
  'getCharCE' must be called on a CHARSXP

,我希望它返回前导和尾随引号,然后将其发送到SQl,它将起作用.

and I would like it to return with the leading and trailing quotes then I can send it on to SQl and it will work.

[1] "select case when "est"  dsaf"

推荐答案

也许您希望看到同一字符串的另一种表示形式:

Perhaps you would like to see a different representation of the same string:

test2 <- 'select case when "est"  dsaf'
test<- "select case when \"est\"  dsaf"
identical(test, test2)
#[1] TRUE

当用双引号构建字符值时,\"的任何内部实例都仅成为双引号.它们将由print(以及您在交互式会话中看到的REPL)显示,并带有转义反斜杠,但是使用cat不能确定它们是否真的不存在反斜杠.

When a character value is built with double quotes, any interior instances of \" become only double-quotes. They will be displayed by print (and by the REPL that you see in an interactive session) with the escape-backslash, but using cat you cant determine that they are not really in there as backslashes.

进一步的证明:

>  nchar("\"")
[1] 1

您可以使用cat或使用quote=FALSE进行打印,以显示实际存在于内部的值:

You can use either cat or print with quote=FALSE in you want to display the value as it really exists internally:

> print(test, quote=FALSE)
[1] select case when "est"  dsaf

这证明,当字符串内部出现\"时,至少有一个版本的"SQL"同意(或接受")没有反斜杠:

This is evidence that at least one version of "SQL" agrees (or "accepts") that there is no backslash when \" appears in the interior of a string:

> require(sqldf)
Loading required package: sqldf
Loading required package: gsubfn
Loading required package: proto
Loading required package: RSQLite
Loading required package: DBI
> ?sqldf
> a1r <- head(warpbreaks)
> a1s <- sqldf("select * from warpbreaks limit 6")
Loading required package: tcltk
> a2s <- sqldf("select * from CO2 where Plant like 'Qn%'")
> 
> a2sdq <- sqldf("select * from CO2 where Plant like \"Qn%\"")
> identical(a2s,a2sdq)
[1] TRUE

这篇关于从字符串中删除反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆