Home > other >  How to add Brackets around a word which is between certain characters using Regex?
How to add Brackets around a word which is between certain characters using Regex?

Time:11-04

I am trying to add brackets around a string which is segeraged by some characters;

For example, I have a string like: "Red => Orange => Yellow blue => Grey,black"

I would like to get something like "[ Red ] => [ Orange ] => [ Yellow blue ] => [ Grey,black ]" (space before and brackets also present)

I have tried several approaches in R using stingr package but I am unable to get this above pattern.

Thanks in advance for your help

I have tried to use stringr function in R str_replace_all(str,"\b\w ","[\1]") and str_replace_all(str,"\b\w ","[") but the function replaces the character specified, I am unable to find a method to replace before a character

CodePudding user response:

You can use

x <- "Red => Orange => Yellow blue => Grey,black"
paste0("[ ", paste(strsplit(x, " => ", fixed=TRUE)[[1]], collapse=" ] => [ "), " ]")
paste0("[ ", gsub("\\s*=>\\s*", " ] => [ ", x), " ]")

See the R demo. Both solutions yield [1] "[ Red ] => [ Orange ] => [ Yellow blue ] => [ Grey,black ]".

The gsub("\\s*=>\\s*", " ] => [ ", x) part replaces all occurrences of zero or more whitespaces, =>, zero or more whitespaces with space ] => [ space.

paste0("[ ", gsub(...), " ]") is used to enclose the whole string with [ and ].

  • Related