【问题标题】:Replacing multiple ocurrences of a text between two patterns [duplicate]替换两个模式之间多次出现的文本[重复]
【发布时间】:2018-10-04 15:01:09
【问题描述】:

我有一个 data.frame,其中有一列包含客户数字路径(见下文)。在每一行中,我想用“推荐”一词替换 > 和 _referral 之间的所有文本。

例如下面的 3 行

bing_cpc>uswitch.com_referral
bing_cpc>money.co.uk_referral
bing_cpc>moneysupermarket.com_referral>google_organic>moneysupermarket.com_referral>google_cpc>google_cpc

应该是

bing_cpc>Referral
bing_cpc>Referral
bing_cpc>Referral>google_organic>Referral>google_cpc>google_cpc

有什么想法吗? 谢谢

【问题讨论】:

  • 欢迎来到 SO!请阅读How to make a great R reproducible example? 并根据它编辑您的问题。为了帮助您,我们需要使用 dput() 函数发布的数据示例和所需结果示例。
  • 你有什么尝试吗?你到底是在哪里卡住的?当您搜索“r 字符串替换”时,您肯定会发现一些有用的资源。
  • @cheikh;让您了解反对票。每个人都在这里提供帮助,但请记住,您所在的社区主要由忙碌的专业人士组成,要求他们花费时间和精力来解决您的问题。除了参与社区并做同样的事情,最好的回报方式是make a good question。这不仅有利于整个网站,还可以帮助您:解决一个好问题通常会引导您找到可能的解决方案。

标签: r


【解决方案1】:

试用:

df$col <- gsub(">.*referral", ">Referral", df$col)

【讨论】:

    【解决方案2】:

    您的问题比看起来更棘手,因此值得详细回答。首先,让我们把你的例子放在一个向量中:

    exStrg <- c(
      'bing_cpc>uswitch.com_referral',
      'bing_cpc>money.co.uk_referral',
      'bing_cpc>moneysupermarket.com_referral>google_organic>moneysupermarket.com_referral>google_cpc>google_cpc'
    )
    

    您想要的是将遵循模式“>xxxxx_referral”的所有内容替换为“>Referral”。 gsub 是它的函数,直接模式是 '>.*_referral',点表示“任何字符”,星号表示“随时发生”。但是*+ 通配符是贪婪的,所以会发生这种情况:

    > gsub(pattern = '>.*_referral', replacement = '>Referral', exStrg)
    [1] "bing_cpc>Referral"                      
    [2] "bing_cpc>Referral"                      
    [3] "bing_cpc>Referral>google_cpc>google_cpc"
    

    表达式将采用第一个“>”和最后一个“_referral”之间的任何内容。您可以使用? 使通配符变得懒惰;这将识别您的模式的多次出现,但仍将中间的所有内容:

    > gsub('>.*?_referral', '>Referral', exStrg)
    [1] "bing_cpc>Referral"                               
    [2] "bing_cpc>Referral"                               
    [3] "bing_cpc>Referral>Referral>google_cpc>google_cpc"
    

    您需要将任何后续的“>”表示为否定字符:

    > gsub('>[^>]*_referral', '>Referral', exStrg)
    [1] "bing_cpc>Referral"                                              
    [2] "bing_cpc>Referral"                                              
    [3] "bing_cpc>Referral>google_organic>Referral>google_cpc>google_cpc"
    

    【讨论】:

    • 非常感谢。成功了!
    • 大家好,UK|BP_Brand_Products_e_def >(不可用)> UK|B_Brand_Pure Other_e_def > UK|B_Brand_Pure Only_e_def > UK|NB_Pure Only_e_def
    • 嗨 Carlos,在下文中,我将如何将遵循模式 > UK|B_Brandxxxxx 的任何内容替换为 > Brand
    • UK|BP_Brand_Products_e_def > (不可用)> UK|B_Brand_Pure Other_e_def > UK|B_Brand_Pure Only_e_def > UK|NB_Pure Only_e_def
    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2021-07-02
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多