简体   繁体   中英

How to use REGEXP in sqlQuery function in R

EDIT-1

My actual database is in MSAccess format and I am importing the data using sqlQuery function in RODBC package of R. The following is fake database I am creating so that I can provide a reproducible example using RSQLite package. I want to use regexp with the sqlQuery function.

End of EDIT-1

The following is a mock database and associated queries using RSQLite package. The REGEX (or REGEXP ) function does not work and I could not figure out why.

data0 <- read.csv(textConnection(
'ID  value
P9W38   97
P9W39   17
P9W40   78
P9W41   7
P9W42_1 38
P9W42   13
P9W43   18
P9W44   76
P9W45   65
P9W46   24
P9W46_1 44
P9W47   8
P9W48   31
P9W49   82
P9W50   52
P9W50_2 55
P9W51   26
P9W52   33
P9W52_2 79
P9W53   67
P9W54   74
P9W55   55'
),sep='')

dbWriteTable(con, "Mydata", data0)

These worked

dbGetQuery(con, paste0(' select * from Mydata where [ID] like \'P9W38\' '))
dbGetQuery(con, paste0(' select * from Mydata where [ID] like \'P9W42%\' '))

But these do not work

dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEX \'P9W(38|40|50)\' '))
dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEX \'P9W(38|40|50)(_1){,1}\' '))

Any suggestion?

I think your problem is inside the query you have REGEX instead of REGEXP:

http://dev.mysql.com/doc/refman/5.1/en/regexp.html

so your code should be like:

dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEXP \'P9W(38|40|50)\' '))
dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEXP \'P9W(38|40|50)(_1){,1}\' '))

give some feedback please, I don't work much with databases, but I think that will solve your problem

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