Regex removing multiple brackets

Viewed 347

Hi I have a string that looks like string = "Tom (Marketing Assistant)/Gary (Manager)/Forty" and I want to remove all the parts inside the brackets such that the outcome is "Tom/Gary/Forty".

I've tried string %>% str_remove("\\(.+\\)") but the output is "Tom /Forty" and it seems that because the regex matching takes the very first ( and up till the very last ) which I tried visualizing with string %>% str_extract("\\(.+\\)") which gives "(Marketing Assistant)/Gary (Manager)". I can't specify too specific what is inside the bracket because there is a range of characters in the brackets (not all the same), so is there a way to code it in a way that only removes what is inside the brackets, possibly by telling it to stop removing once it encounters / because this follows every bracket?

2 Answers

We can also do

library(stringr)
str_replace_all(string, "[(][^)]+[)]", "")
#[1] "Tom /Gary /Forty"

Use str_remove_all to remove all the occurrences.

stringr::str_remove_all(string, '\\(.*?\\)')
#[1] "Tom /Gary /Forty"

In base R, use gsub -

gsub('\\(.*?\\)', '', string)

This removes all the characters between opening and closing round brackets. Question mark (?) makes the regex non-greedy so it matches only till the first closing bracket. All such occurrences are removed since we are using str_remove_all/gsub.

Related