【问题标题】:R gsub multiple conditionsR gsub 多重条件
【发布时间】:2016-08-02 14:59:31
【问题描述】:

我正在尝试在一组可能在措辞上略有不同的字符串上使用 gsub;

I went to the store last night
I went to the park yesterday
I went to starbucks this morning

我需要使用 gsub 来替换 'I going to...',但有时它会有一个 'the',有时它不会

类似这样的东西,但以下将无法正常工作

gsub('i went to [the|a-z]','REPLACED',string)

REPLACED last night
REPLACED yesterday
REPLACED this morning

【问题讨论】:

  • 这样的? gsub("I went to[ the]*(store|park|starbucks)","REPLACED",data)
  • @user2100721 我相信他把它放在第二个代码块中。
  • @user2100721 它位于第二个块中。谢谢

标签: r gsub


【解决方案1】:

试试:

gsub("I went to (the )?[a-z]", "REPLACED", string)

【讨论】:

  • 这会将 store|park|starbucks 留在字符串中
  • 据我了解,这种输出是意料之中的
  • 据我了解,REPLACED last night REPLACED yesterday REPLACED this morning 是预期的
  • 您可以使用I went to (the )?[a-z]* 删除store|park|starbucks
  • gsub("我去了(the) [a-z]+","REPLACED", string)
【解决方案2】:

您可以将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()

【讨论】:

    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多