简体   繁体   English

使用r将单词中的匹配单词替换为单词

[英]replacing a matching word in a string by a word using r

I am trying to replace a string with a word after having found a match. 找到匹配项后,我试图用一个单词替换一个字符串。

I have the following words: 我有以下几句话:

bigrams = c("technical lead", "project engineer", "head of")

and the following string: 和以下字符串:

string = c("technical lead rotatives", "resident project engineer", "head of medicine", "senior project engineer")

I would like the answer to be: 我希望答案是:

answer = c("technical lead", "project engineer", "head of", "project engineer")

I have tried various things such as: 我尝试过各种方法,例如:

gsub("^(\\w).* project engineer$", " project engineer", string)

which only works for a case. 仅适用于情况。 Any help. 任何帮助。 Sorry I am not very good at working with strings. 抱歉,我不是很擅长处理字符串。 thanks! 谢谢!

Have a look at stringr package, it makes life easier: https://stringr.tidyverse.org/ 看看stringr包,它使生活更轻松: https : stringr

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM