gpt4 book ai didi

regex - 从字符串向量中提取数字

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

我有这样的字符串:

years<-c("20 years old", "1 years old")

我只想 grep 来自该向量的数字。预期输出是一个向量:

c(20, 1)

我该如何去做呢?

最佳答案

怎么样

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))

关于regex - 从字符串向量中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543627/

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