【问题标题】:Replace slash with a single backslash in R用R中的单个反斜杠替换斜杠
【发布时间】:2020-01-17 08:03:54
【问题描述】:

这可能是微不足道的,但我没有找到任何关于这个确切问题的问题。 我的问题与提出合适的正则表达式无关,它与准确指定替换部件有关。

x = "file_path/file_name.txt" - this is what I have
# "file_path\file_name.txt" - this is what I want

这是我尝试过的:

library(stringr)
str_detect(string = x, pattern = "/") # returns TRUE, as expected
#str_replace_all(string = x, pattern = "/", replacement = "\") # fails, R believes I'm escaping the quote in the replacement
str_replace_all(string = x, pattern = "/", replacement = "\\") # this results to "file_pathfile_name.txt", missing the backslash altogether
str_replace_all(string = x, pattern = "/", replacement = "\\\\") # this results to "file_path\\file_name.txt", which is not what I want

任何帮助将不胜感激。

【问题讨论】:

    标签: r character-replacement


    【解决方案1】:

    解决办法是转义转义字符,最后是4个'\'。

    cat(gsub('/', '\\\\', "file_path/file_name.txt"))
    

    查看标准输出与转义转义字符的“print()”或使用“cat()”获取纯字符串之间的区别。

    str_replace_all(string = x, pattern = "/", replacement = "\\\\")
    cat(str_replace_all(string = x, pattern = "/", replacement = "\\\\"))
    

    【讨论】:

    • 这是我的代码的最后一行。它只是看起来正确,因为您使用了cat()。我错过了什么吗?
    • 刚刚在我的回答中添加了这一点。 Cat 没有转义特殊字符...您的最后一行是正确的,只是看起来不正确。你需要习惯 R 中的这种行为 :-)
    • 我明白:“\\”是我真正想要的。非常感谢您帮助我实现这一点。
    猜你喜欢
    • 2017-07-25
    • 2012-06-16
    • 1970-01-01
    • 2023-03-16
    • 2023-02-07
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多