假设我有这个物体
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,但它没有给我想要的输出。
gsub
使用正确的正则表达式可以正常工作:
gsub('^(.*)(,| except).*$', '\\1', x)
#> [1] "keep this text" "keep this part"
或者请尝试 stringr::str_remove_all
str_remove_all(x,'((?=\\,).*)|((?=except).*)')
[1] "keep this text " "keep this part"
为了避免复杂的正则表达式,我们可以使用
stringr
依次删除文本
library(stringr)
x |>
str_remove_all(",.*") |>
str_remove_all(" except.*")
[1] "keep this text" "keep this part"