简体   繁体   English

使用Regex检查'%'字符的MySQL查询值

[英]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 \\% . 我想检查MySQL Query的值是否包含%字符(可以多次出现)但不包含转义的\\%

So it should match: 所以它应该匹配:

  • '%test'
  • '%test\\%'
  • 'test\\\\%' - should match because it's escape the \\ not the % 'test\\\\%' - 应该匹配,因为它逃脱了\\而不是%
  • '%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. 我正在尝试创建一个用于从数组生成SQL查询的PHP库,并且生成的查询可能主要用于MySQL。
So, the regex filtering process will be in PHP. 因此,正则表达式过滤过程将使用PHP。

Sorry, I forgot to mention this. 对不起,我忘了提这个。

Thanks 谢谢

Assuming SQL Server, this should work: 假设SQL Server,这应该工作:

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: 在PHP代码上检查:

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 http://ideone.com/Bgq5bV

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM