我正在将一个短语读入R脚本作为参数。如果该短语包含星号(*),则我不希望脚本运行。
但是,使用grepl时,我在识别星号时遇到了问题。例如:
> asterisk="*"
> phrase1="hello"
> phrase2="h*llo"
> grepl(asterisk,phrase1)
[1] TRUE
> grepl(asterisk,phrase2)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
的结果grepl(asterisk,phrase1)应为FALSE。有谁知道我如何grepl识别短语中是否有星号?
尝试这个:
p <- c("Hello", "H*llo")
grepl("\\*", p)
[1] FALSE TRUE
Run Code Online (Sandbox Code Playgroud)
之所以起作用,是因为*星号在正则表达式中具有特殊含义。具体来说,*意味着找到零个或多个先前元素。
因此,您必须使用来使星号转义\\*。两次转义是必要的,因为R中\已经具有转义的含义。