R regex从矢量中获得了一年

时间:2018-01-30 06:15:48

标签: r regex

好的正则表达式正式成为我存在的祸根。

我需要一个子表达式来将年份作为R中的单独字符向量:

vector <- c("Hello_world_1999_otherstuff.file", "Hello_2010_world_otherstuff.file", "2015_hello_world_help_me_thanks!.file")

vector.desired <- c("1999", "2010", "2015")

谢谢!

3 个答案:

答案 0 :(得分:3)

libray(stringr)
str_extract(vector, "\\d{4}")

答案 1 :(得分:2)

使用基础R中的sub

vector <- c("Hello_world_1999_otherstuff.file", "Hello_2010_world_otherstuff.file", "2015_hello_world_help_me_thanks!.file")
years <- sub(".*(?:^|_)(\\d{4})(?:_|$).*", "\\1", vector)

years
[1] "1999" "2010" "2015"

Demo

答案 2 :(得分:2)

使用base r

 regmatches(vector,regexpr("\\d{4}",vector))
[1] "1999" "2010" "2015"

如果在年份之前有其他值,请使用环顾四周,您可以使用:

 regmatches(vector,regexpr("(?<=^|_)\\d{4}(?=_|$)",vector,perl = T))
[1] "1999" "2010" "2015" "1999"