Reputation: 41
I'm trying to find the right regex to grepl weather a string contains digits[0-9] and the special character "-" only.
ex,
str1="00-25" #TRUE
str2="0a-2" #FALSE
I have tried
grepl("[^[:digit:]|-]",str2)
#[1] TRUE
thoughts?
Upvotes: 2
Views: 5043
Reputation: 2480
You want to check if the string has only digit and -.
To create the ensemble, you need to use "[]" so :
[0-9-]
Now you want to check that every character of the string is in the ensemble you have created, in other term you want to start(^) and finish($) by this ensemble :
^[0-9-]$
Finally in the variable there is 1 or more character, so I use the "+" :
grepl("^[0-9-]+$",str)
Upvotes: 3