如何在活动记录where子句中正确地转义正则表达式

时间:2022-10-06 14:04:28

I am using Active Record v4.2.1 to query a mySQL database using a regular expression. I would like to create the following SQL:

我正在使用Active Record v4.2.1使用正则表达式查询mySQL数据库。我想创建以下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.

但是,我似乎无法找到使用活动记录创建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?

如何获取活动记录以正确地转义SQL?

1 个解决方案

#1


2  

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.

您可以在控制台中运行实际的查询并检查日志文件来确认这一点。

#1


2  

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.

您可以在控制台中运行实际的查询并检查日志文件来确认这一点。