使用stringr从R中的系列中提取最后4位数字

Dan*_*iel 7 regex r stringr

我想展平从HTML表中提取的列表.下面介绍一个最小的工作示例.该示例取决于stringrR中的包.第一个示例表现出所需的行为.

years <- c("2005-", "2003-")
unlist(str_extract_all(years,"[[:digit:]]{4}"))

[1] "2005" "2003"
Run Code Online (Sandbox Code Playgroud)

当我尝试匹配一系列其他数字中的最后4位数时,下面的示例会产生不良结果.

years1 <- c("2005-", "2003-", "1984-1992, 1996-")
unlist(str_extract_all(years1,"[[:digit:]]{4}$"))

character(0)
Run Code Online (Sandbox Code Playgroud)

据我理解文档,我应该包含$在模式的末尾,以便在字符串的末尾请求匹配.我更愿意从第二个例子中匹配数字,"2005","2003"和"1996".

Ric*_*ven 8

stringi软件包具有方便的功能,可以对字符串的特定部分进行操作.因此,您可以使用以下内容找到最后一次出现的四个连续数字.

library(stringi)

x <- c("2005-", "2003-", "1984-1992, 1996-")

stri_extract_last_regex(x, "\\d{4}")
# [1] "2005" "2003" "1996"
Run Code Online (Sandbox Code Playgroud)

获得相同结果的其他方法是

stri_sub(x, stri_locate_last_regex(x, "\\d{4}"))
# [1] "2005" "2003" "1996"

## or, since these count as words
stri_extract_last_words(x)
# [1] "2005" "2003" "1996"

## or if you prefer a matrix result
stri_match_last_regex(x, "\\d{4}")
#      [,1]  
# [1,] "2005"
# [2,] "2003"
# [3,] "1996"
Run Code Online (Sandbox Code Playgroud)


jba*_*ums 7

你可以sub很容易地使用base R :

sub('.*(\\d{4}).*', '\\1', years1)

## [1] "2005" "2003" "1996"
Run Code Online (Sandbox Code Playgroud)

这里匹配的模式是.*(零个或多个任何字符)后跟\\d{4}(四个连续数字,我们通过括在括号中捕获),后跟零个或多个字符.

sub将匹配的模式替换为第二个参数中的值.在这种情况下,\\1表示我们想要用第一个捕获的子串(即四个连续的数字)替换整个匹配的模式.

正则表达式是贪婪的,所以它会绕过早期的匹配\\d{4},消耗它们.*.仅捕获四个连续数字的最后序列.