我正在R中处理字符串,这些字符串应该包含零个或一个括号对。如果有嵌套的括号,我需要删除内部的括号。下面是一个例子,我需要删除big bent nachos周围的括号,但不删除其他/外部的括号。
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?"
)
我知道可以使用 stringr
包的 str_remove_all()
方法来删除所有括号:
test |>
stringr::str_remove_all(stringr::fixed(")")) |>
stringr::str_remove_all(stringr::fixed("("))
但我没有正则表达式技能来获取内部括号。我找到了一个与之接近的SO文章,但它删除了外部括号,我无法解开它以删除内部括号。
here(a(b(c)))
,您想要here(a)
还是here(abc)
? - Onyambu(
和)
字符,而内容需要保留。 - itsMeInMiamihere(abc)
吗?你最多只有一个嵌套的括号还是多个嵌套的括号? - Onyambu\(([^)(]*)\)(?=(?:[^)(]*\([^)(]*\))*[^)(]*\))
(替换为$1
) - 如果有嵌套,则使用递归正则表达式:(?:\G(?!^)|\()[^)(]*\K(\(((?>[^)(]+|(?1))*)\))
(替换为$2
) - 使用gsub
(perl=T
) - bobble bubble