Replacing white space with one single backslash

后端 未结 2 1136
青春惊慌失措
青春惊慌失措 2020-12-07 03:49

I want to replace a white space with ONE backslash and a whitespace like this:

\"foo bar\" --> \"foo\\ bar\"

I found how to replace wit

相关标签:
2条回答
  • 2020-12-07 04:03

    To replace a space with one backslash and a space, you do not even need to use regular expression, use your gsub(" ", "\\ ", x) first attempt with fixed=TRUE:

    > x <- "foo bar" 
    > res <- gsub(" ", "\\ ", x, fixed=TRUE)
    > cat(res, "\n")
    foo\ bar 
    

    See an online R demo

    The cat function displays the "real", literal backslashes.

    0 讨论(0)
  • 2020-12-07 04:06

    Your problem is a confusion between the content of a string and its representation. When you print out a string in the ordinary way in R you will never see a single backslash (unless it's denoting a special character, e.g. print("y\n"). If you use cat() instead, you'll see only a single backslash.

    x <- "foo bar"
    y <- gsub(" ", "\\\\ ", x)
    print(y)
    ## [1] "foo\\ bar"
    cat(y,"\n")  ## string followed by a newline
    ## foo\ bar
    

    There are 8 characters in the string; 6 letters, one space, and the backslash.

    nchar(y)  ## 8
    

    For comparison, consider \n (newline character).

    z <- gsub(" ", "\n ", x)
    print(z)
    ## [1] "foo\n bar"
    cat(z,"\n")
    ## foo
    ##  bar 
    nchar(z)  ## 8
    

    If you're constructing file paths, it might be easier to use forward slashes instead - forward slashes work as file separators in R on all operating systems (even Windows). Or check out file.path(). (Without knowing exactly what you're trying to do, I can't say more.)

    0 讨论(0)
提交回复
热议问题