#1139 - 从正则表达式中得到错误“重复运算符操作数无效"

2021-11-20 00:00:00 regex select mysql

我在使用正则表达式从 MySQL 表中选择一些结果时遇到问题.

I'm having trouble using a regular expression to select some results from my MySQL table.

我正在使用这个查询

SELECT text 
FROM `articles` 
WHERE content REGEXP '.*<img.*?src=\"http://www' 
ORDER BY date DESC

它说

#1139 - Got error 'repetition-operator operand invalid' from regexp

我用 Notepad++ 测试了正则表达式,它有效,为什么 MySQL 给我这个错误,我该如何解决?

I tested the regex with Notepad++ and it works, why MySQL is giving me this error and how can i fix it?

推荐答案

根据MySQL 手册

MySQL 使用 Henry Spencer 的正则表达式实现,旨在符合 POSIX 1003.2

MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2

POSIX 正则表达式不支持使用问号 ? 作为星号的非贪婪(懒惰)修饰符以及 PCRE(Perl 兼容正则表达式)等量词.这意味着你不能使用 +?*?

POSIX regexes don't support using the question mark ? as a non-greedy (lazy) modifier to the star and plus quantifiers like PCRE (Perl Compatible Regular Expressions). This means you can't use +? and *?

看起来你只需要使用贪婪的版本,它应该仍然有效.为了避免<img style="/*some style*/" src="a.png"><script src="www.example.com/js/abc.js">,可以使用否定字符类:

It looks like you'll just have to use the greedy version, which should still work. To avoid the matching of things like <img style="/*some style*/" src="a.png"> <script src="www.example.com/js/abc.js">, you can use a negated character class:

']*src="http://www'

注意:" 不必转义,开头的 .* 是隐含的.

Note: The " doesn't have to escaped and the .* at the beginning is implied.

相关文章