如何删除模式之前的所有内容?

How to remove everything before pattern?

我试图删除模式之前的所有内容,但是当它有一个“?”时和空格我认为它不起作用。

question <- "How much do you agree or disagree to the following statements? - I am happy"
str_remove(question, "How much do you agree or disagree to the following statements? - ")
[1] "How much do you agree or disagree to the following statements? - I am happy"

如果我这样做,我会得到这个:

str_remove(question, "How much do you agree or disagree to the following statements?")
[1] "? - I am happy"

最后我只想得到这个:

[1] "I am happy"

我们可能会更改模式以匹配字符 (.*) 后跟 ?(元字符 - 所以转义 \),后跟一个或多个空格 (\s+) 然后是 - 和一个空格 (\s+)

library(stringr)
str_remove(question, ".*\?\s+-\s+")
[1] "I am happy"

base R中,使用trimws

trimws(question, whitespace = ".*\?\s+-\s+")
[1] "I am happy"

看起来 ? 被解释为正则表达式量词 (https://www.rexegg.com/regex-quickstart.html)。

您可以使用 fixed=TRUE 从字面上解释模式。

question <- "How much do you agree or disagree to the following statements? - I am happy"

sub(pattern = "How much do you agree or disagree to the following statements? - ",
    replacement = "",
    x = question,
    fixed = TRUE)
[1] "I am happy"