我試圖洗掉模式之前的所有內容,但是當它有一個“?” 和空格我認為它不起作用。
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"
uj5u.com熱心網友回復:
我們可以更改模式以匹配字符 ( .*) 后跟?(元字符 - 所以轉義\\),后跟一個或多個空格 ( \\s ) 然后 a-和多個空格之一 ( \\s )
library(stringr)
str_remove(question, ".*\\?\\s -\\s ")
[1] "I am happy"
在base R,使用trimws
trimws(question, whitespace = ".*\\?\\s -\\s ")
[1] "I am happy"
uj5u.com熱心網友回復:
它看起來像是?被解釋為一個正則運算式量詞(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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/339997.html
