Replace text between two special characters

2019-02-27 04:07发布

问题:

I have a character vector as:

x<- "\t\t<taxon id=\"TOT_F50\"/>"

and

 y<- "TOT_A01"

and I want replace TOT_F50 with the text in y ("TOT_A01").

Do you know how to replace the text between " and \ (i.e. "TOT_F50) ?

回答1:

Try

 sub('(?<=").*(?=")', y, x, perl=TRUE)
 #[1] "\t\t<taxon id=\"TOT_A01\"/>"


回答2:

I would use something like

gsub("\".*\"", paste0("\"", y, "\""), x)

It just means "find text within two quotation marks in x and replace it with y inside two quotation marks"

I think this is what you want, your example is wrong though