简体   繁体   中英

keep original string in the replacement text R

I want to match some expressions and quote them;

input: gene_id TM_000000132331; transcript_id ENST_0000001435435.2;

output: gene_id "TM_000000132331"; transcript_id "ENST_0000001435435.2";

how can I do it? using gsub or str_replace, whatever..?

In the gsub call, parenthesize the part of pattern you want to enclose in double quotes, and use \1 to refer to matched substrings in replacement :

x <- "gene_id TM_000000132331; transcript_id ENST_0000001435435.2;"
gsub("(\\S+);", "\"\\1\";", x)
## [1] "gene_id \"TM_000000132331\"; transcript_id \"ENST_0000001435435.2\";"

You can search "backreference" in ?regex for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM