简体   繁体   English

使用 cat() 从字符串中删除 \"

[英]Removing \" from string with cat()

I can't understand why #3 doesn't give me xxx"yyy .我不明白为什么#3不给我xxx"yyy

xxx\\\"yyy" %>% cat() results in xxx\"yyy which is input of #2 . I would expect that the second cat() in #3 would give the same result as running #2 . xxx\\\"yyy" %>% cat()结果xxx\"yyy#2的输入。我希望#3中的第二个cat()会给出与运行#2相同的结果。

library(tidyverse)

#1
"xxx\"yyy"
#> [1] "xxx\"yyy"

#2
"xxx\"yyy" %>% cat()
#> xxx"yyy

#3
"xxx\\\"yyy" %>% cat() %>% cat()
#> xxx\"yyy

Created on 2021-03-02 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2021 年 3 月 2 日创建

I got stuck with that when loading a text file with readr's read_file() which converts \"\", \"SQL\" in file to \\\"\\\", \\\"SQL\\\" in string.我在使用 readr 的read_file()加载文本文件时遇到了这个问题,它将文件中的\"\", \"SQL\"转换为字符串中的\\\"\\\", \\\"SQL\\\" .

I would like to get string with "", "SQL" .我想用"", "SQL"获取字符串。

I can't understand why #3 doesn't give me xxx"yyy .我不明白为什么#3 不给我xxx"yyy

In a nutshell, because … %>% cat() %>% cat() makes no sense.简而言之,因为… %>% cat() %>% cat()没有意义。 cat() has no return value. cat()没有返回值。 It writes the result to a file (which might be an output stream).它将结果写入文件(可能是 output 流)。

So there's no value to be piped into the second cat() invocation argument list.所以没有值可以通过管道传递到第二个cat()调用参数列表中。 Remember that a %>% b() is just a different way of writing b(a) .请记住, a %>% b()只是b(a)的另一种写法。 You're executing cat(cat(…)) .你正在执行cat(cat(…))

If you want to unescape a string, don't use cat() .如果要取消转义字符串,请不要使用cat() Use sub() or str_replace() from 'stringr'.使用“stringr”中的sub()str_replace() Though if you're depending on 'stringr' anyway you might find it more convenient to use the function stringi::stri_unescape_unicode , which does exactly that, and 'stringi' is imported by 'stringr' anyway (so it's not an additional dependency).虽然如果你仍然依赖'stringr',你可能会发现使用 function stringi::stri_unescape_unicode更方便,它就是这样做的,并且'stringi'无论如何都是由'stringr'导入的(所以它不是额外的依赖项) .

We can use我们可以用

cat('xxx"yyy', '\n')
 #xxx"yyy 

Or pass it as an r' string literally without the need to escape anything或将其作为r'字符串逐字传递,而无需转义任何内容

r"{xxx"yyy"}" %>%
    cat
#xxx"yyy"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM