Remove quotes from string at the beginning and end only if both are present

I want to clear a string containing escaped quotes. I want to remove the escaped quotation marks as the end and the beginning of the line, but keep the integrity of all the Qoutation characters in the line. I came up with the following.

library(stringr)
s1 <- "\"He said:\"Hello\" - some word\""
str_replace_all(s1, "(^\\\")|(\\\"$)", "")

> [1] "He said:\"Hello\" - some word"

What I'm struggling with right now is that I only want to remove quotes if and only if there is one at the beginning and at the end. Otherwise, no. The following expression falsely removes the lead.

s2 <- "\"Hello!\" he said"
str_replace_all(s2, "(^\\\")|(\\\"$)", "")

> [1] "Hello!\" he said"

Here, my regex should indicate that I want to remove them only if the entire string is wrapped in escaped quotes. How can i do this?

+5
source share
1 answer

For your examples, the following regex seems to work:

s <- c("\"He said:\"Hello\" - some word\"", "\"Hello!\" he said")

regex (\\1), ^\" - \"$:

r <- gsub("^\"(.*)\"$", "\\1", s)

:

cat(r, sep="\n")
He said:"Hello" - some word
"Hello!" he said
+7

All Articles