5

I am using SQL and need to check if a string contains a certain substring using regular expressions. Lower and upper case letters and space are allowed.

Currently, I have Where description = '/^[a-zA-Z\s]mysubstring[a-zA-Z\s]$/'

But it is not working for some reason. Any idea?

4
  • Which RDMS are you using? Commented Mar 4, 2017 at 20:51
  • It looks like you are not using the pattern correctly. It should look like WHERE description REGEXP '^[[:alpha:][:space:]]*mysubstring[[:alpha:][:space:]]*$' Commented Mar 4, 2017 at 20:51
  • You can simply use LIKE statement , to check the substring Commented Mar 4, 2017 at 20:52
  • @sumit: WHERE description LIKE '%mysubstring%' will find entries that may contain more than just letters and whitespace. Ke Zhang, please check what is working for you best. Commented Mar 4, 2017 at 20:52

1 Answer 1

5

MySQL regex is not supporting the same syntax as PHP PCRE regex. If you want to use a regex check, you must use the REGEXP operator. Next, it does not support \s and other shorthand classes, you need to replace it with a [:space:] POSIX character class.

Also, MySQL REGEXP will perform a case insensitive regex check by default, but you still can use [A-Za-z] just in case you have non-standard options.

Use

WHERE description REGEXP '^[a-zA-Z[:space:]]*mysubstring[a-zA-Z[:space:]]*$'

If you do not care about what there is in the entries and you just need to find those containing your string, use LIKE with % (=any text) wildcard:

WHERE description LIKE '%mysubstring%'
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.