[英]How to properly escape a regular expression in Active Record where clause
I am using Active Record
v4.2.1
to query a mySQL
database using a regular expression. 我使用Active Record
v4.2.1
使用正则表达式查询mySQL
数据库。 I would like to create the following SQL: 我想创建以下SQL:
SELECT `users`.* FROM `users` WHERE (email REGEXP '[@\.]gmail\.com')
However, I cannot seem to find the correct way to create the SQL using Active Record. 但是,我似乎无法找到使用Active Record创建SQL的正确方法。
User.where("email REGEXP ?", "[@.]gmail.com").to_sql
yields 产量
"SELECT `users`.* FROM `users` WHERE (email REGEXP '[@.]gmail.com')"
User.where("email REGEXP ?", "[@\.]gmail\.com").to_sql
yields 产量
"SELECT `users`.* FROM `users` WHERE (email REGEXP '[@.]gmail.com')"
User.where("email REGEXP ?", "[@\\.]gmail\\.com").to_sql
yields 产量
"SELECT `users`.* FROM `users` WHERE (email REGEXP '[@\\\\.]gmail\\\\.com')"
How do I get Active Record to properly escape the SQL? 如何获取Active Record以正确转义SQL?
The escaping just looks wrong in the console when using to_sql
, your last example actually sends this to MySQL: 使用to_sql
,在控制台中转义只是看起来不对,你的最后一个例子实际上是将它发送给MySQL:
SELECT `users`.* FROM `users` WHERE (email REGEXP '[@\\.]gmail\\.com')
You can confirm this by running the actual query in the console and checking the log file. 您可以通过在控制台中运行实际查询并检查日志文件来确认这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.