如何在Mysql中正则表达式中转义特殊的SQL字符

Dae*_*ead 9 regex mysql

我有一个文本字段来接受来自UI的正则表达式.对于这些正则表达式,我有搜索功能,并希望进行搜索.我正在使用预准备语句,DB是mysql.当我在'%'上搜索时,我只想要以'%'开头的搜索正则表达式.但是,因为'%'是mysql中的通配符,所以我在搜索中获得所有正则表达式.如何逃避它.

Don*_*nut 11

只需在字符前使用反斜杠,如MySQL文档部分9.1所示:

\0  An ASCII NUL (0x00) character.  
\'  A single quote ("'") character.  
\"  A double quote (""") character.  
\b  A backspace character.  
\n  A newline (linefeed) character.  
\r  A carriage return character.  
\t  A tab character.  
\Z  ASCII 26 (Control+Z). See note following the table.  
\\  A backslash ("\") character.  
\%  A "%" character. See note following the table.  
\_  A "_" character. See note following the table.  
Run Code Online (Sandbox Code Playgroud)

注意(来自MySQL文档):

如果在模式匹配上下文之外使用"\%"或"\ _",它们将评估字符串"\%"和"\ _",而不是"%"和"_".