The idea is to add quotation marks for all strings inside an string list representation.
Tried the next:
input_text <- "[innovation manager, manager director, senior manager]"
scan(text=input_text, what="")
Which returns:
'[innovation" "manager," "manager" "director," "senior" "manager]'
Expected output could look like this:
'["innovation manager", "manager director", "senior manager"]'
What am I missing?
CodePudding user response:
One method - remove the square brackets with gsub
, split at the ,
(strsplit
), extract the list element, insert the double quotes (dQuote
), and paste
the split elements together
sprintf('[%s]', paste(dQuote(strsplit(gsub("[][]", "", input_text),
",\\s*")[[1]], FALSE), collapse=", "))
-output
[1] "[\"innovation manager\", \"manager director\", \"senior manager\"]"
CodePudding user response:
A possible solution;
library(tidyverse)
input_text <- "[innovation manager, manager director, senior manager]"
input_text %>%
str_remove_all("\\[|\\]") %>%
str_split(", ") %>% unlist
#> [1] "innovation manager" "manager director" "senior manager"
But, if the OP wants the result as a single string, one can use the following:
input_text %>%
str_remove_all("\\[|\\]") %>%
str_split(", ") %>%
map(~ str_c('"',.x, '"')) %>% unlist %>%
str_flatten(collapse = ", ") %>%
str_c("[",.,"]")
#> [1] "[\"innovation manager\", \"manager director\", \"senior manager\"]"