Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grepl in R to search for an asterisk

Tags:

r

I am reading a phrase into an R script as an argument. If the phrase contains an asterisk (*), I do not want the script to run.

However, I am having issues recognising the asterisk when using grepl. For example:

> asterisk="*"
> phrase1="hello"
> phrase2="h*llo"
> grepl(asterisk,phrase1)
[1] TRUE
> grepl(asterisk,phrase2)
[1] TRUE

The outcome for grepl(asterisk,phrase1) should be FALSE. Does anyone know how I can get grepl to recognise if there is or isn't an asterisk in the phrase?

like image 953
IcedCoffee Avatar asked Dec 25 '22 07:12

IcedCoffee


1 Answers

Try this:

p <- c("Hello", "H*llo")
grepl("\\*", p)

[1] FALSE  TRUE

This works because the * asterisk has special meaning in a regular expresssion. Specifically, * means find zero or more of the previous element.

Thus you have to escape the asterisk using \\*. The double escape is necessary because the \ already has the meaning of escape in R.

like image 95
Andrie Avatar answered Jan 08 '23 18:01

Andrie