R 字符串在括号上拆分,将括号及其内容保留在拆分中

R string split on parentheses, keeping the parentheses in the split with its content

我正在尝试拆分某种格式的字符串

x <- "A(B)C"

其中 A、B 和 C 可以是空字符串或除括号外的任何字符集。括号总是在那里 - 我想将它们放在它们所包含的字符周围,这样结果就是:

"A" "(B)" "C"

到目前为止我最好的尝试是:

strsplit(x, "(?<=\))|(?=\()", perl = TRUE)
[[1]]
[1] "A"  "("  "B)" "C"

但这使左括号分开。有什么想法吗?

您可以使用

x <- "A(B)C"
library(stringr)
str_extract_all(x, "\([^()]*\)|[^()]+")

R demo and the regex demo详情:

  • \([^()]*\) - (,除 () 之外的零个或多个字符,然后是 )
  • | - 或
  • [^()]+ - ().
  • 以外的一个或多个字符
library(stringr)

x <- c("A(B)C", "ABC", "0$b")
stringr::str_extract_all(x, "[\(]?.{1}[\)]?")

# [[1]]
# [1] "A"   "(B)" "C"  
# 
# [[2]]
# [1] "A" "B" "C"
# 
# [[3]]
# [1] "0" "$" "b"