Delete string parts within delimiter

Viewed 56

I have a string as"dfgdf" sa"2323":

a <- "as\"dfgdf\" sa\"2323\""

The delimiter (same for the start and the end) here is ". So what I want is to get a string were everything is deleted within delimiter but not delimiter itself. So the end result string should look like as"" sa""

4 Answers

You could match " and forget what is matched using \K

Then use a negated character class matching any char except " or a whitespace character and use lookarounds to assert " to the right.

Use perl=TRUE to enable Perl-like regular expressions.

a <- "as\"dfgdf\" sa\"2323\""
gsub('"\\K[^"\\s]+(?=")', "", a, perl=TRUE)

Output

[1] "as\"\" sa\"\""

R demo

Here is another base R option using paste0 + strsplit

s <- paste0(paste0(unlist(strsplit(a, '"\\w+"')), '""'), collapse = "")

which gives

> s
[1] "as\"\" sa\"\""
> cat(s)
as"" sa""

Here is one option with a regex lookaround to match a word (\\w+) that succeeds a double quote and precedes one as pattern and is replaced by blank ("")

cat(gsub('(?<=")\\w+(?=")', "", a, perl = TRUE), "\n")
#as"" sa"" 

Or without regex lookaround

cat(gsub('"\\w+"', '""', a), "\n")
#as"" sa"" 

I also found a way with stringr library:

library(stringr)

a <- "as\"dfgdf\" sa\"2323\""

result <- str_replace_all(a, "\".*?\"", "\"\"")
cat(result)
Related