【发布时间】:2018-05-15 14:22:48
【问题描述】:
我想使用stringr 包删除所有与字符串模式不匹配的字符。到目前为止,我已经能够使用"\\w+(?= (grape|satsuma))" 作为模式删除模式之前的那些,但在模式仍然不可能之后删除那些。
> str_remove_all("apples grape banana melon olive persimon grape apples satsuma papaya",
+ "\\w+(?= (grape|satsuma))")
[1] " grape banana melon olive grape satsuma papaya"
想要的结果是:
"grape grape satsuma"
(注意:我知道在这种情况下最简单的方法是仅提取“葡萄”和“萨摩”,但出于分析目的,我更喜欢这种方式)
已编辑提供整个问题
整个问题如下,给定一个 d 数据框,其中包含一个带有字符串的列,该函数应仅在匹配时返回同一列:
> d
# A tibble: 2 x 2
string_column c2
<chr> <dbl>
1 apples grape banana satsuma 3
2 grape banana satsuma melon 4
使用@d.r 提供的答案有效:
> d %>%
+ mutate_at(vars(string_column), ~ gsub("(grape|satsuma| )(*SKIP)(*FAIL)|.", "", ., perl = TRUE))
# A tibble: 2 x 2
string_column c2
<chr> <dbl>
1 " grape satsuma" 3
2 "grape satsuma " 4
到目前为止使用stringr 包提供的所有答案都无法返回string_column
这是dput 的d:
d <- structure(list(string_column = c("apples grape banana satsuma",
"grape banana satsuma melon"), c2 = c(3, 4)), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))
【问题讨论】:
-
gsub("(grape|satsuma| )(*SKIP)(*FAIL)|.", "", "apples grape banana melon olive persimon grape apples satsuma papaya", perl = TRUE) -
@d.b 是的!但我想使用
stringr包,有什么想法吗? -
使用
str_remove_all和"\\w+(?= (grape|satsuma))"作为模式删除grape或satsuma之前的单词。我的期望结果是str_remove_all删除所有与papaya或satsuma不匹配的内容,因此在这种情况下的期望结果是:"grape grape satsuma"。请让我知道目的是否不够明确。