Search code examples
rstringquotesgsubbraces

Substituting braces {} with quotes "


I want to replace braces {} with quotes ". I tried the following code, the problem is that the \ appaers in the string and I can not delete it.

Code used:

makebib <- function(string){
   # replace { by "
   string <- gsub("\\{",'"',string)

   # replace } by "
   string <- gsub("\\}",'"',string)

   # delete \
   string <- gsub("\\","",string,fixed = TRUE)

   return(string)
}

test <- "bla{bla}"
makebib(test)

[1] "bla\"bla\""

How can I manage that the \ does not appears or delete it?


Solution

  • Your function works. The \ isn't really there.

    Consider the following:

    test <- "bla{bla}"
    makebib(test)
    # [1] "bla\"bla\""
    
    cat(makebib(test))
    # bla"bla"
    
    nchar(makebib(test))
    # [1] 8
    

    By the way, your function could also be simplified:

    makebib <- function(string) gsub("[{}]", "\"", string)