You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串向量中提取特定单词后的5个单词短语?

提取目标球队后5个单词的解决方案

原代码仅匹配了Brazil或Argentina本身,要实现提取目标单词后5个单词的需求,可通过扩展正则表达式完成,具体实现如下:

完整代码

library(stringr)

my_text <- "The World Cup 2022 winners, Argentina, have failed to dislodge Brazil from the top of the Fifa men’s world rankings as England remains fifth in the post-Qatar standings.
Had Argentina won the final within 90 minutes, they would have taken the top spot from Brazil. In the last eight tournaments going back to USA 94, no team leading the rankings at kick-off has won the tournament, with only Brazil, the 1998 finalists, getting beyond the quarter-finals."

my_teams <- tolower(c("Brazil", "Argentina"))

# 构建正则模式:匹配完整球队名,再捕获后续1-5个单词(兼容标点分隔)
pattern <- paste0("\\b(", paste(my_teams, collapse = "|"), ")\\b(?:\\W+\\w+){1,5}")

# 提取所有符合条件的片段,支持大小写不敏感匹配
matches <- unlist(str_extract_all(my_text, pattern, ignore.case = TRUE))

# 将所有片段合并为完整字符串
result <- paste(matches, collapse = " ")

print(result)

关键细节说明

  • \\b:单词边界,确保只匹配完整的球队名称,避免误抓类似Brazilian这类包含球队名的衍生单词
  • (?:\\W+\\w+){1,5}:非捕获组,用来匹配球队名后的1到5个单词——\\W+处理空格、逗号等分隔符,\\w+匹配单词本身
  • ignore.case = TRUE:无需提前将文本转小写,直接支持大小写不敏感匹配

运行结果

Argentina, have failed to dislodge Brazil from the top of Argentina won the final within Brazil, the 1998 finalists, getting beyond

内容的提问来源于stack exchange,提问作者Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:00:42