gpt4 book ai didi

使用正则表达式删除父括号

转载 作者:行者123 更新时间:2023-12-03 07:52:11 25 4
gpt4 key购买 nike

希望就我认为简单的正则表达式问题获得一些帮助。我想从字符串中删除父括号集,但保留子括号。例如:

gsub(some regex ,"LOG((X))")  

会返回

(X)

我已经接近了

 gsub("LOG\\(|\\)","","LOG((X))")

但是这会返回

 (X

有什么建议吗?

最佳答案

也许有点太强大了,但如果你想要一个具有所有级别嵌套的向量,你可以这样做:

v <- c("LOG(EXP(X))", "A", "EXP(LOG(2*SIN(X)))")


unnest_parentheses <- function(x) {

lapply(x, \(x) {

start <- gregexpr("\\(", x)[[1]]
end <- rev(gregexpr("\\)", x)[[1]])

if (length(start) != length(end)) {

stop("We either miss a starting or ending parentheses")

} else {

tree <- unlist(Map(f = \(start, end) {
str_sub(x, start+1, end-1)
}, start, end))
tree <- c(x, tree) # comment out if you not want the parent
tree[tree != ""]

}

})

}

unnest_parentheses(v)

输出

[[1]]
[1] "LOG(EXP(X))" "EXP(X)" "X"

[[2]]
[1] "A"

[[3]]
[1] "EXP(LOG(2*SIN(X)))" "LOG(2*SIN(X))" "2*SIN(X)" "X"

关于使用正则表达式删除父括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76910502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com