5

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.

4
  • What is the error that you're getting? Commented Mar 17, 2018 at 0:58
  • Error Code: 1139. Got error 'repetition-operator operand invalid' from regexp Commented Mar 17, 2018 at 1:01
  • 2
    Double the backslash. MySQL requires the first one to escape the second backslash which so it can be treated as a literal character in the regex (to modify/escape ?) rather than as an escaping character within the SQL itself. Thus use regexp '^\\?.+' Commented Mar 17, 2018 at 1:03
  • Regex is valid regexr.com/3md2b Commented Mar 17, 2018 at 1:05

1 Answer 1

10

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.

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...

Format your expression with an escaped backslash as:

select *
from mytable
where thumbnail_url regexp '^\\?.+'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.