简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM