【问题标题】:mysql: how to escape parenthesis in perl stringmysql:如何在perl字符串中转义括号
【发布时间】:2014-01-24 08:57:04
【问题描述】:

我需要使用正则表达式进行 MySQL 查询,并且部分条件包含括号。
我知道如何在 MySQL 中转义括号......通过使用双反斜杠。
但是,当我将查询放在要在 perl 中使用的字符串中时,这似乎不起作用。
我尝试将字符串括在撇号中,并再次尝试使用引号无济于事。
示例:

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

以上内容在 MySQL 中有效,但在 perl 中出现错误:“括号不平衡”

【问题讨论】:

  • 你能把你的 Perl 代码放在你进行数据库调用的地方吗?
  • @XiVix 您需要格式化代码以显示双反斜杠,看看我是如何编辑您的问题的:) 一般来说,像这样格式化实际代码而不是将其放入文本。
  • 您需要展示您的 Perl 代码,因为这似乎是问题所在。

标签: mysql regex perl escaping parentheses


【解决方案1】:

我想如果你通过了会得到错误

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

而不是

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

你确定你的字符串是正确的吗?我怀疑你实际上构建了以前的字符串。

例如代码

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

产生不需要的字符串

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

代码

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

产生所需的字符串

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

【讨论】:

    【解决方案2】:

    使用 DBI 的 quote 将变量安全地插入 SQL 字符串是最简单的,如果您正在使用裸 SQL(请注意,常见的约定是使用某种 SQL 接口,而不是出于各种原因这超出了这个答案的范围)。

    因此,实现您想要的快速/方便的方法是:

    #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");
    

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 2016-01-13
      • 2011-08-09
      • 2017-07-20
      • 2015-10-01
      • 1970-01-01
      • 2010-12-16
      • 2015-05-16
      相关资源
      最近更新 更多