常规正则表达式:
foo(\((\d{1}|\d{2}|\d{3})\))?
这个正则表达式在 Java 中工作:
foo(\\((\\d{1}|\\d{2}|\\d{3})\\))?
例子:
fooa //no match
foo(1)a //no match
foo(a) //no match
foo(1) //match
foo(999) //match
foo //match
MySQL 5.5 文档(https://dev.mysql.com/doc/refman/5.5/en/regexp.html)说
Note:
Because MySQL uses the C escape syntax in strings (for example, “\n” to
represent the newline character), you must double any “\” that you use
in your REGEXP strings.
我尝试在 MySQL 5.x 上运行以下测试
select 'foo' REGEXP 'foo(\\((\\d{1}|\\d{2}|\\d{3})\\))?'
这是我收到的错误消息:
Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near ''foo(\\([(]\\d{1}' at line 1
我查看了Adapting a Regex to work with MySQL并尝试了用 [0-9] 替换 \d{1} 等的建议,这给了我:
select 'foo' REGEXP 'foo(\\(([0-9]|[0-9]|[0-9])\\))?'
但仍然让 MySQL 死亡。