gpt4 book ai didi

regex - 在字符串中的第一个逗号处拆分

转载 作者:行者123 更新时间:2023-12-02 01:55:37 25 4
gpt4 key购买 nike

如何使用 base 在第一个逗号上有效地拆分以下字符串?

x <- "I want to split here, though I don't want to split elsewhere, even here."
strsplit(x, ???)

期望的结果(2个字符串):

[[1]]
[1] "I want to split here" "though I don't want to split elsewhere, even here."

提前谢谢您。

编辑:没想到提及这一点。这需要能够推广到像这样的列、字符串向量,如下所示:

y <- c("Here's comma 1, and 2, see?", "Here's 2nd sting, like it, not a lot.")

结果可以是两列或一个长向量(我可以获取其中的所有其他元素)或每个索引 ([[n]]) 具有两个字符串的字符串列表。

对于缺乏清晰度表示歉意。

最佳答案

这就是我可能会做的事情。这可能看起来很老套,但由于 sub()strsplit() 都是矢量化的,因此在处理多个字符串时它也能顺利工作。

XX <- "SoMeThInGrIdIcUlOuS"
strsplit(sub(",\\s*", XX, x), XX)
# [[1]]
# [1] "I want to split here"
# [2] "though I don't want to split elsewhere, even here."

关于regex - 在字符串中的第一个逗号处拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309122/

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