我正在尝试在一组字符串上使用gsub,这些字符串可能会略微改变措辞;
I went to the store last night
I went to the park yesterday
I went to starbucks this morning
我需要使用gsub来代替'我去了...',但有时它会有一个''有时它不会
这样的事情,但以下不能正常工作
gsub('i went to [the|a-z]','REPLACED',string)
REPLACED last night
REPLACED yesterday
REPLACED this morning
答案 0 :(得分:2)
尝试:
gsub("I went to (the )?[a-z]", "REPLACED", string)
答案 1 :(得分:0)
您可以将stringr
包与以下正则表达式一起使用(使用^
锚定在字符串的前面):
library(stringr)
sentences <- c("I went to the store last night",
"I went to the park yesterday",
"I went to starbucks this morning")
str_replace(sentences, "^I went to( the)?", "REPLACED")
# [1] "REPLACED store last night" "REPLACED park yesterday"
# [3] "REPLACED starbucks this morning"
如果在同一个字符串中有多个要替换的实例,您可能希望省略^
并使用str_replace_all()