gpt4 book ai didi

regex - 不丢失字符的拆分字符串

转载 作者:行者123 更新时间:2023-12-04 23:03:21 37 4
gpt4 key购买 nike

我希望在某个字符处拆分字符串,同时在第二个结果字符串中保留该字符。我几乎可以实现所有想要的操作,只是我丢失了我在 strsplit 中指定的字符,我猜这被称为分隔符。

有没有办法请求strsplit保留分隔符?或者我必须使用某种正则表达式?谢谢你的任何建议。这似乎是一个非常基本的问题。对不起,如果它是重复的。我更喜欢使用基础 R。

这是一个示例,显示了我到目前为止所拥有的内容:

my.table <- read.table(text = '
model npar AICc
AA(~region+state+county+city)BB(~region+state+county+city)CC(~1) 17 11111.11
AA(~region+state+county)BB(~region+state+county)CC(~123) 14 22222.22
AA(~region+state)BB(~region+state)CC(~33) 13 33333.33
AA(~region)BB(~region)CC(~4321) 6 44444.44
', header = TRUE, stringsAsFactors = FALSE)

desired.result <- read.table(text = '
model CC npar AICc
AA(~region+state+county+city)BB(~region+state+county+city) CC(~1) 17 11111.11
AA(~region+state+county)BB(~region+state+county) CC(~123) 14 22222.22
AA(~region+state)BB(~region+state) CC(~33) 13 33333.33
AA(~region)BB(~region) CC(~4321) 6 44444.44
', header = TRUE, stringsAsFactors = FALSE)

split.model <- strsplit(my.table$model, 'CC\\(')

split.models <- matrix(unlist(split.model), ncol=2, byrow=TRUE, dimnames = list(NULL, c("model", "CC")))

desires.result2 <- data.frame(split.models, my.table[,2:ncol(my.table)])
desires.result2

# model CC npar AICc
# 1 AA(~region+state+county+city)BB(~region+state+county+city) ~1) 17 11111.11
# 2 AA(~region+state+county)BB(~region+state+county) ~123) 14 22222.22
# 3 AA(~region+state)BB(~region+state) ~33) 13 33333.33
# 4 AA(~region)BB(~region) ~4321) 6 44444.44

最佳答案

基本思想是使用look-around从正则表达式到 strsplit 的操作得到你想要的结果。然而,它比strsplit 有点棘手。和积极的前瞻。阅读 this excellent post来自@JoshO'Brien 的解释。

pattern <- "(?<=\\))(?=CC)"
strsplit(my.table$model, pattern, perl=TRUE)
# [[1]]
# [1] "AA(~region+state+county+city)BB(~region+state+county+city)"
# [2] "CC(~1)"

# [[2]]
# [1] "AA(~region+state+county)BB(~region+state+county)"
# [2] "CC(~123)"

# [[3]]
# [1] "AA(~region+state)BB(~region+state)" "CC(~33)"

# [[4]]
# [1] "AA(~region)BB(~region)" "CC(~4321)"

当然,我离开了 do.call(rbind, ...)的任务和 cbind得到最后的 desired.output给你。

关于regex - 不丢失字符的拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17623147/

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