Bogaso
Bogaso

Reputation: 3308

Pattern match with grepl() function in R

I am confused on below result on pattern match using grepl() function -

grepl("[0-9]{2}-[0-9]{2}-[0-9]{2}", "2010-04-09") # TRUE
grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", "2010-04-09")  #TRUE

Shouldn't I expect the first result to be FALSE?

Any pointer will be highly appreciated.

Upvotes: 2

Views: 512

Answers (1)

Fleur De Lys
Fleur De Lys

Reputation: 480

The result is correct.

grepl is looking for the pattern of xx-xx-xx, where x is a digit, and that does appear in the first query. If you want to query starting from the beginning of the string, you can use the ^ symbol.

For example, if you were to run grepl("^[0-9]{2}-[0-9]{2}-[0-9]{2}", "2010-04-09"), you'd get FALSE, but grepl("^[0-9]{4}-[0-9]{2}-[0-9]{2}", "2010-04-09") would return TRUE.

PS: On the opposite end, $ indicates the end of the string.

Upvotes: 5

Related Questions