代码之家  ›  专栏  ›  技术社区  ›  Minh Chau

删除字符串中某个“短语”后的剩余字符串(R)

  •  0
  • Minh Chau  · 技术社区  · 2 年前

    假设我有这个物体

    x <- c('keep this text except remove this part after a certain phrase','keep this part, remove everything after the comma')

    我想使用Stringr来删除(1)单词“except”之后的所有内容&(2) 在“,”之后

    我想要的x输出是:

    'keep this text'

    'keep this part'

    有办法在R中做到这一点吗?

    我尝试使用gsub,但它没有给我想要的输出。

    3 回复  |  直到 2 年前
        1
  •  1
  •   Allan Cameron    2 年前

    gsub 使用正确的正则表达式可以正常工作:

    gsub('^(.*)(,| except).*$', '\\1', x)
    #> [1] "keep this text" "keep this part"
    
        2
  •  1
  •   jkatam    2 年前

    或者,请尝试字符串::str_remove_all

    str_remove_all(x,'((?=\\,).*)|((?=except).*)')
    
    [1] "keep this text " "keep this part" 
    
        3
  •  1
  •   GuedesBF    2 年前

    为了避免使用复杂的正则表达式,我们可以使用按顺序删除文本 stringr

    library(stringr)
    
    x |> 
        str_remove_all(",.*") |>
        str_remove_all(" except.*")
    
    [1] "keep this text" "keep this part"