我试图找到一个匹配项后用一个单词替换一个字符串。
我有以下几句话:
bigrams = c("technical lead", "project engineer", "head of")
和以下字符串:
string = c("technical lead rotatives", "resident project engineer", "head of medicine", "senior project engineer")
我希望答案是:
answer = c("technical lead", "project engineer", "head of", "project engineer")
我尝试了各种事情,例如:
gsub("^(\\w).* project engineer$", " project engineer", string)
仅适用于案例。任何帮助。抱歉,我不是很擅长处理字符串。 谢谢!
答案 0 :(得分:2)
看看stringr
包,它使生活更轻松:https://stringr.tidyverse.org/
library(stringr)
bigrams = c("technical lead", "project engineer", "head of")
string = c("technical lead rotatives", "resident project engineer", "head of medicine", "senior project engineer")
answer = c("technical lead", "project engineer", "head of", "project engineer")
pattern <- paste(bigrams, collapse = "|")
result <- str_extract(string, pattern)
identical(answer, result)
# TRUE