Question

I need to do a MySQL query using regex and part of the criteria contains parenthesis.
I know how to escape parenthesis in MySQL ... by using dual backslash.
But this does not seem to work when I put the query in a string to be used in perl.
I've tried enclosing the string in apostrophe, and tried again using quotes to no avail.
example:

select * from table where fieldname regexp '.\\(.';

The above works from MySQL but gives me error in perl: "parentheses not balanced"

Was it helpful?

Solution

I imagine that error would be obtained if you passed

select * from table where fieldname regexp '.\(.';

instead of

select * from table where fieldname regexp '.\\(.';

Are you sure you built your string correctly? I suspect you actually built the former strings.

For example, the code

"select * from table where fieldname regexp '.\\(.';"

produces the undesirable string

select * from table where fieldname regexp '.\(.';

while the code

"select * from table where fieldname regexp '.\\\\(.';"

produces the desired string

select * from table where fieldname regexp '.\\(.';

OTHER TIPS

It is easiest to use DBI's quote to safely interpolate variables into SQL strings, if you are working with naked SQL (note the common convention is to use a SQL interface of some sort, instead, for a whole slew of reasons which escape the scope of this answer).

So the quick/convenient way to achieve what you want is this:

#Assume $dbi is a handle to your database.
my $reg = $dbh->quote(".\\(.");
my $sth = $dbh->prepare("select * from mailone where msub regexp $reg limit 1");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top