Regex - Replace "((" and "))" by "[" and "]"

Hi,

I would like, using str_replace function, replace "((" by "[" and "))" by "]".
I suppose i should use reg expressions and.. i don't have the knowledge..

Basically, not working :

str_replace("((hello))","((","[")
str_replace("((hello))","))","[")

Expected result :
[hello]

Thanks

Really straightforward with base::grep:

sub(pattern = "((",
    replacement = "[",
    x = sub(pattern = "))",
            replacement = "]",
            x = "((hello))",
            fixed = TRUE),
    fixed = TRUE)
#> [1] "[hello]"

If you want stringr, this may be one option:

library(stringr)

"((hello))" %>%
    str_replace(pattern = fixed(pattern = "(("),
                replacement = "[") %>%
    str_replace(pattern = fixed(pattern = "))"),
                replacement = "]")
#> [1] "[hello]"
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.