Hello my dear teachers/ fellow R users,
I have recently started learning regex in earnest and recently I've come across a case where we only would like to keep paired parentheses () and omit the unpaired ones. Here is my sample data:
structure(list(t1 = c("Book (Pg 1)", "(Website) Online)", "Journal: 2018)",
"Book1 (pg 2) book 3 (pg4) something)")), class = "data.frame", row.names = c(NA,
-4L))
And my desired output would be like:
structure(list(t1 = c("Book (Pg 1)", "(Website) Online", "Journal: 2018",
"Book1 (pg 2) book 3 (pg4) something")), class = "data.frame", row.names = c(NA,
-4L))
I myself have managed to do it with the following code, but I thought there is surely a more efficient way of going about it. As a matter of fact I would like to learn other ways of doing getting the similar result:
test$t2 <- gsub("([(]?.*[)]?\\s+[^(]\\w+)[)]|([(].*[)])", "\\1\\2", test$t1)
test
t1 t2
1 Book (Pg 1) Book (Pg 1)
2 (Website) Online) (Website) Online
3 Journal: 2018) Journal: 2018
4 Book1 (pg 2) book 3 (pg4) something) Book1 (pg 2) book 3 (pg4) something
Another issue with my regex is when I swap the places of RHS and LHS of | it does not lead to the desired result which I'm curious why.
I would be grateful if you could give a little bit of explanation on solving these sorts of problem.
Thank you very much in advance.