从字符串向量中提取数字

时间:2013-01-27 01:47:43

标签: regex r

我有这样的字符串:

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

我想只使用此向量中的数字grep。预期输出是一个向量:

c(20, 1)

我该怎么做?

11 个答案:

答案 0 :(得分:64)

怎么样

# 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))

答案 1 :(得分:46)

我认为替代是获得解决方案的间接方式。如果您想要检索所有数字,我建议gregexpr

matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
as.numeric(unlist(matches))

如果字符串中有多个匹配项,则会获得所有匹配项。如果您只对第一场比赛感兴趣,请使用regexpr代替gregexpr,您可以跳过unlist

答案 2 :(得分:41)

<强>更新 由于不推荐使用extract_numeric,我们可以使用parse_number包中的readr

library(readr)
parse_number(years)

以下是extract_numeric

的另一个选项
library(tidyr)
extract_numeric(years)
#[1] 20  1

答案 3 :(得分:30)

以下是Arun第一个解决方案的替代方案,它具有更简单的类似Perl的正则表达式:

as.numeric(gsub("[^\\d]+", "", years, perl=TRUE))

答案 4 :(得分:19)

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

答案 5 :(得分:16)

stringr流水线解决方案:

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

答案 6 :(得分:15)

你也可以摆脱所有的字母:

as.numeric(gsub("[[:alpha:]]", "", years))

虽然这可能不那么普遍。

答案 7 :(得分:4)

从开头位置的任何字符串中提取数字。

x <- gregexpr("^[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

从任意位置的字符串中提取数字。

x <- gregexpr("[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

答案 8 :(得分:2)

来自 Gabor Grothendieck的帖子 post at the r-help mailing list

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

library(gsubfn)
pat <- "[-+.e0-9]*\\d"
sapply(years, function(x) strapply(x, pat, as.numeric)[[1]])

答案 9 :(得分:2)

我们还可以使用str_extract中的stringr

years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20  1

如果字符串中有多个数字,并且我们想提取所有数字,则可以使用str_extract_all,它与str_extract不同,它返回所有宏。

years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20"  "1"

stringr::str_extract_all(years, "\\d+")

#[[1]]
#[1] "20" "21"

#[[2]]
#[1] "1"

答案 10 :(得分:0)

使用软件包 unglue 我们可以做到:

# install.packages("unglue")
library(unglue)

years<-c("20 years old", "1 years old")
unglue_vec(years, "{x} years old", convert = TRUE)
#> [1] 20  1

reprex package(v0.3.0)于2019-11-06创建

更多信息:https://github.com/moodymudskipper/unglue/blob/master/README.md