亲爱的老师们/各位 R 用户,大家好,
我最近开始认真学习正则表达式,最近我遇到了一个案例,我们只想保留成对的括号 ()
并省略未配对的。这是我的 样本数据 :
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))
还有我的 所需的输出 会像: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))
我自己已经设法用下面的代码来做到这一点,但我认为肯定有一种更有效的方法来解决它。事实上,我想学习其他获得类似结果的方法: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
我的正则表达式的另一个问题是当我交换 RHS
的位置时和 LHS
的 |
它不会导致预期的结果,我很好奇为什么。如果您能就解决此类问题给出一些解释,我将不胜感激。
非常感谢您提前。
最佳答案
非常直接:
\([^()]*\)(*SKIP)(*FAIL)|[()]+
与 perl = T
范围。稍微解释一下:
\([^()]*\)(*SKIP)(*FAIL) # match any balanced parenthesis construct and let the engine skip it
| # or
[()]+ # match single parentheses
阅读 more on backtracking control verbs并查看 a demo on regex101.com .
关于r - 如何只删除单括号并保留成对的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68239696/