Home > Back-end >  How to remove everything before pattern?
How to remove everything before pattern?

Time:10-29

I'm trying to remove everything before a pattern, but when it has a "?" and whitespaces I think it doesn't work.

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"

If I do this I get this:

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

In the end I'm looking to get only this:

[1] "I am happy"

CodePudding user response:

We may change the pattern to match characters (.*) followed by ? (metacharacter - so escape \\), followed by one or more spaces (\\s ) then a - and one of more spaces (\\s )

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

In base R, use trimws

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

CodePudding user response:

It looks like ? is being interpreted as a regex quantifier (https://www.rexegg.com/regex-quickstart.html).

You can use fixed=TRUE to interpret the pattern literally.

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"
  • Related