简体   繁体   中英

Checking MySQL Query value for '%' character with Regex

I want to check if a value for a MySQL Query contain % character (can appear multiple times) but not the escaped \\% .

So it should match:

  • '%test'
  • '%test\\%'
  • 'test\\\\%' - should match because it's escape the \\ not the %
  • '%test\\%%'
  • '\\%test%test\\%'

but not:

  • 'test\\%'
  • '\\%test\\%'
  • '\\%test\\%test\\%'

I'm not good in Regular Expression, can someone help me on this?

Thanks in advance.

Edit :
I'm trying creating a PHP Library for generating SQL Query from an array, and maybe the generated query will be used mostly on MySQL.
So, the regex filtering process will be in PHP.

Sorry, I forgot to mention this.

Thanks

Assuming SQL Server, this should work:

WHERE
  ColumnX LIKE '%[%]%' ESCAPE '\'

Though I'm not sure if it handles \\\\% correctly.

This should work in any case:

WHERE
  REPLACE(REPLACE(ColumnX, '\\', ''), '\%', '') LIKE '%[%]%'

Check this on PHP code:

unset($str1,$str2,$str3,$str4,$str5,$str6,$str7);

$str1 = '%100'; 
$str2 = '%100\%';
$str3 = "100\\\\%";
$str4 = "%100\\%%";
$str5 = '100\%';
$str6 = "100\\\\\\\\%";
$str7 = "100\\\\\\%";
$str8 = "100\\\\\\\\\\\\%";
$str9 = "100\\\\\\\\\\\\\\%";

$reg_exp=  '/^%|[^\x5C]%|[^\x5C](\x5C\x5C)+%/';

echo $str1.' = '.preg_match($reg_exp, $str1).'<br />';
echo $str2.' = '.preg_match($reg_exp, $str2).'<br />';
echo $str3.' = '.preg_match($reg_exp, $str3).'<br />';
echo $str4.' = '.preg_match($reg_exp, $str4).'<br />';
echo $str5.' = '.preg_match($reg_exp, $str5).'<br />';
echo $str6.' = '.preg_match($reg_exp, $str6).'<br />';
echo $str7.' = '.preg_match($reg_exp, $str7).'<br />';
echo $str8.' = '.preg_match($reg_exp, $str8).'<br />';
echo $str9.' = '.preg_match($reg_exp, $str9).'<br />';

http://ideone.com/Bgq5bV

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