如何移除R语言字符串中的内层嵌套括号?
解决方案
可以使用stringr包的str_replace_all()结合正则表达式,精准匹配并删除内层括号:
library(stringr) test <- c( "Record ID", "What is the best food? (choice=Nachos)", "What is the best food? (choice=Tacos (big bent nachos))", "What is the best food? (choice=Chips with stuff)", "Complete?" ) # 删除内层括号 result <- str_replace_all(test, "(?<=[(][^()]*)\\(|\\)(?=[^()]*[)])", "") print(result)
输出结果
[1] "Record ID" [2] "What is the best food? (choice=Nachos)" [3] "What is the best food? (choice=Tacos big bent nachos)" [4] "What is the best food? (choice=Chips with stuff)" [5] "Complete?"
正则表达式说明
(?<=[(][^()]*)\\(:匹配外层括号内部的左括号,通过正向断言确保该左括号前是外层左括号,且中间无其他括号干扰\\)(?=[^()]*[)]):匹配外层括号内部的右括号,通过正向断言确保该右括号后是外层右括号,且中间无其他括号干扰- 用
|连接两种匹配规则,一次性替换所有内层的(和)
多层嵌套场景处理
如果存在多层嵌套(比如(a(b(c)))),可以循环执行替换直到没有内层括号残留:
# 处理多层嵌套的情况 result_multi <- test while(str_detect(result_multi, "(?<=[(][^()]*)\\(|\\)(?=[^()]*[)])")) { result_multi <- str_replace_all(result_multi, "(?<=[(][^()]*)\\(|\\)(?=[^()]*[)])", "") } print(result_multi)
内容的提问来源于stack exchange,提问作者itsMeInMiami
相关产品推荐
相关产品推荐

