首页 > 解决方案 > 如何删除一组特定字符之前的所有内容(例如,“? - ”)?

问题描述

我想删除“? - ”之前的所有内容,包括字符本身(问号、空格、连字符、空格)。我知道可以删除特定字符之前的所有内容。我不想只删除连字符 - 之前的所有内容,因为我还有其他带有连字符的语句。我试过这个,但它不适用于连字符。

例子:

gsub(".*-", "", "To what extent do you disagree or agree with the following statements? - Statistics make me cry.")
gsub(".*-", "", "To what extent do you disagree or agree with the following statements? - T-tests are easy to interpret.")

Output:
" Statistics make me cry."
"tests are easy to interpret."

我希望第二个语句显示为T-tests are easy to interpret

标签: rstringtidyversestringr

解决方案


这里sub就足够了,而不是 global g。更改模式以匹配?(元字符 - 所以它被转义\\),后跟零个或多个空格 ( \\s*) -,然后是零个或多个空格,替换为空白 ( '')

sub(".*\\?\\s*-\\s*", "", v1)
#[1] "Statistics make me cry."        "T-tests are easy to interpret."

数据

v1 <- c("To what extent do you disagree or agree with the following statements? - Statistics make me cry.", 
"To what extent do you disagree or agree with the following statements? - T-tests are easy to interpret."
)

推荐阅读