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

问题描述 投票:0回答:3

假设我有这个物体

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,但它没有给我想要的输出。

r stringr gsub
3个回答
0
投票

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

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

0
投票

或者请尝试 stringr::str_remove_all

str_remove_all(x,'((?=\\,).*)|((?=except).*)')

[1] "keep this text " "keep this part" 

0
投票

为了避免复杂的正则表达式,我们可以使用

stringr

依次删除文本
library(stringr)

x |> 
    str_remove_all(",.*") |>
    str_remove_all(" except.*")

[1] "keep this text" "keep this part"
© www.soinside.com 2019 - 2024. All rights reserved.