gpt4 book ai didi

R 拆分字符串并保留匹配右侧的子字符串?

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

如何在 R 中执行此字符串 split()?当没有用破折号分隔的名字时停止拆分。保留结果中给出的右侧子字符串。

a <- c("tim/tom meyer XY900 123kncjd", "sepp/max/peter moser VK123 456xyz")

# result:
c("tim meyer XY900 123kncjd", "tom meyer XY900 123kncjd", "sepp moser VK123 456xyz", "max moser VK123 456xyz", "peter moser VK123 456xyz")

最佳答案

这是使用几个不同的基本字符串函数的一种可能性。

## get the lengths of the output for each first name
len <- lengths(gregexpr("/", sub(" .*", "", a), fixed = TRUE)) + 1L
## extract all the first names
## using the fact that they all end at the first space character
fn <- scan(text = a, sep = "/", what = "", comment.char = " ")
## paste them together
paste0(fn, rep(regmatches(a, regexpr(" .*", a)), len))
# [1] "tim meyer XY900 123kncjd" "tom meyer XY900 123kncjd"
# [3] "sepp moser VK123 456xyz" "max moser VK123 456xyz"
# [5] "peter moser VK123 456xyz"

添加: 这是第二种可能性,使用较少的代码。也可能会快一点。
s <- strsplit(a, "\\/|( .*)")
paste0(unlist(s), rep(regmatches(a, regexpr(" .*", a)), lengths(s)))
# [1] "tim meyer XY900 123kncjd" "tom meyer XY900 123kncjd"
# [3] "sepp moser VK123 456xyz" "max moser VK123 456xyz"
# [5] "peter moser VK123 456xyz"

关于R 拆分字符串并保留匹配右侧的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35226958/

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