1

在使用 str_match 找到第一个“匹配”后,是否有停止搜索的选项?相当于grep的“m”的东西?我查看了 stringr 包,但找不到任何东西。也许我错过了?

在给定的字符串中:

str <- "This is a 12-month study cycle"

我正在使用以下内容来提取: 12-month from it

str_match(str, "(?i)(\\w+)[- ](month|months|week|weeks)")[1]

但是如果字符串 str 扩展到:

"This is a 12-month study cycle. In the 2 month period,blah blah...".

我希望搜索停止并检索 12 个月,而不是同时获得:12 个月和 2 个月。知道我该怎么做吗?

4

2 回答 2

3

这个怎么样 ?

str <- "This is a 12-month study cycle"    
regmatches(str, regexpr("(?i)(\\w+)[- ](month|months|week|weeks)", str) )

[1]“12个月”

str2 <- "This is a 12-month study cycle. In the 2 month period,blah blah..."
regmatches(str2, regexpr("(?i)(\\w+)[- ](month|months|week|weeks)", str2) )

[1]“12个月”

于 2013-07-16T08:17:02.663 回答
0

试试stringi包。如果您想匹配所有,请使用stri_match_all_regex,如果只是第一次或最后一次使用stri_match_first_regexor stri_match_last_regex

    stri_match_first_regex(str, "(?i)(\\w+)[- ](month|months|week|weeks)")
     [,1]       [,2] [,3]   
[1,] "12-month" "12" "month"

 stri_match_all_regex(str, "(?i)(\\w+)[- ](month|months|week|weeks)")
[[1]]
     [,1]       [,2] [,3]   
[1,] "12-month" "12" "month"
[2,] "2 month"  "2"  "month"
于 2013-07-16T10:42:52.243 回答