在mySQL正则表达式中转义问号

时间:2021-04-09 22:25:20

I have this simple query that uses regex. I don't know why it returns an error every time I try to run it.

我有这个使用正则表达式的简单查询。我不知道为什么每次我尝试运行它都会返回错误。

select *
from mytable
where thumbnail_url regexp '^\?.+'

Basically, I want to see if any string in this list starts with a question mark or not. I am connected to Amazon RDS through MySQLWorkbench 6.3.

基本上,我想看看这个列表中的任何字符串是否以问号开头。我通过My​​SQLWorkbench 6.3连接到Amazon RDS。

1 个解决方案

#1


3  

When you use a backslash to escape a regexp character in MySQL, you must also escape the backslash itself as \\. MySQL would see a single \ character and attempt to use it as an escaping character within the SQL statement itself rather than treating it as a literal. But you need it to act as a literal in order to modify the ? within the regex.

当您使用反斜杠来转义MySQL中的正则表达式字符时,您还必须将反斜杠本身转义为\\。 MySQL会看到一个\字符,并尝试将其用作SQL语句本身的转义字符,而不是将其视为文字。但你需要它作为文字来修改?在正则表达式内。

The first \ escapes the second \, resulting in a literal regex sequence \? to represent a single literal ? in the matching string.

第一个\转义第二个\,导致文字正则表达式序列\?代表单个文字?在匹配的字符串中。

MySQL documentation on string literals...

关于字符串文字的MySQL文档......

Format your expression with an escaped backslash as:

使用转义反斜杠格式化表达式:

select *
from mytable
where thumbnail_url regexp '^\\?.+'

#1


3  

When you use a backslash to escape a regexp character in MySQL, you must also escape the backslash itself as \\. MySQL would see a single \ character and attempt to use it as an escaping character within the SQL statement itself rather than treating it as a literal. But you need it to act as a literal in order to modify the ? within the regex.

当您使用反斜杠来转义MySQL中的正则表达式字符时,您还必须将反斜杠本身转义为\\。 MySQL会看到一个\字符,并尝试将其用作SQL语句本身的转义字符,而不是将其视为文字。但你需要它作为文字来修改?在正则表达式内。

The first \ escapes the second \, resulting in a literal regex sequence \? to represent a single literal ? in the matching string.

第一个\转义第二个\,导致文字正则表达式序列\?代表单个文字?在匹配的字符串中。

MySQL documentation on string literals...

关于字符串文字的MySQL文档......

Format your expression with an escaped backslash as:

使用转义反斜杠格式化表达式:

select *
from mytable
where thumbnail_url regexp '^\\?.+'