0

I have the following string which I would like to remove the parentheses and the text within from. I do not understand regex so is there another method to remove it. I want to use R to do this

Code:
Objects <- "Wood (Brown), leaves (Green), Sky (Blue)"

End Result:
Objects <- "Wood, leaves, Sky"

Logica
  • 977
  • 4
  • 16
  • 1
    relevant (possible duplicate): https://stackoverflow.com/questions/24173194/remove-parentheses-and-text-within-from-strings-in-r – Sotos Jan 24 '20 at 11:02
  • Hi Sotos, I did see this but I could not understand the solution :) – Hanish Kiran Sanghrajka Jan 24 '20 at 11:04
  • 1
    Hi. Yes, It is slightly overfitted to that specific usecase (at least the accepted answer). That's why I didn't close the question and just left it as a comment – Sotos Jan 24 '20 at 11:05
  • Does this answer your question? [Remove parentheses and text within from strings in R](https://stackoverflow.com/questions/24173194/remove-parentheses-and-text-within-from-strings-in-r) – camille Jan 24 '20 at 15:36

2 Answers2

1

We can try using gsub here for a base R option:

Objects <- "Wood (Brown), leaves (Green), Sky (Blue)"
gsub("\\s*\\(.*?\\)\\s*", "", Objects)

[1] "Wood, leaves, Sky"

Here is the regex pattern being used, followed by an explanation:

\s*\(.*?\)\s*

\s*   match (optional) whitespace before the opening (
\(    match a literal (
.*?   match all content inside the (...)
\)    match a literal (
\s*   match (optional) whitespace after the closing )

Note that we use \s* on both sides of the pattern, to also capture and remove any unwanted whitespace which might be left over after the replacement.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Here is another Base R solution using strsplit()

s <- paste0(unlist(strsplit(Objects,split = "\\s\\(.*?\\)")),collapse = "")

or

s <- paste0(trimws(unlist(strsplit(Objects,split = "\\(.*?\\)"))),collapse = "")

such that

> s
[1] "Wood, leaves, Sky"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81