R gsub多个条件

时间:2016-08-02 14:59:32

标签: r gsub

我正在尝试在一组字符串上使用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

2 个答案:

答案 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()