简体   繁体   中英

Passing parameters to SQL regular expressions

I was wondering if it is possible to pass parameters to regular expressions as if they were literal strings in the MySQL REGEXP function. What I would like to do is the following:

SELECT ? REGEXP CONCAT('string', ?, 'string')

Now when I pass a dot (".") to the second parameter, it will automatically match any character, as expected. This means that strings like "stringastring" and "stringbstring" match the pattern. I wondered if it is possible to match the literal dot only, so as to only match "string.string" in this case. Is there a way to do such a thing with a MySQL regular expression, that does not involve explicitly escaping the parameter (which defeats the purpose of passing parameters in this first place)?

Try putting brackets, as in:

SELECT ? REGEXP CONCAT('string', '[.]', 'string')

See here: http://sqlfiddle.com/#!2/a3059/1

If I understand your question correctly I think you are looking for this:

SELECT ? REGEXP CONCAT('string', REPLACE(?, '.', '[.]'), 'string')

using the REPLACE function, any dot is always escaped to [.], but all others special characters are passed literally.

For those who are using PHP and looking for answer related to this I found an answer related to this in stackover here , though not directly for MySQL queries. The idea is to use preg_quote() to escape regexp meta characters. But in your case you have to apply it twice to your parameter.

$param = preg_quote(preg_quote($param))

Then

SELECT ? REGEXP CONCAT('string', $param, 'string')

Read this article and the comments to find out more

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