使用str_match找到第一个“匹配”后是否可以选择停止搜索?相当于grep的“m”的东西?我看了一下stringr包,但找不到任何东西。也许我错过了它?
在给定的字符串中:
str <- "This is a 12-month study cycle"
我正在使用以下内容提取:从中提取12个月
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个月。知道我怎么能这样做吗?
答案 0 :(得分: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个月”
答案 1 :(得分:0)
试用stringi
套餐。如果您想匹配所有内容,请使用stri_match_all_regex
,如果只是第一个或最后一个使用stri_match_first_regex
或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"