3

How to write a regular expression to match a string if at least 3 characters from the start are matching?

Here is how my MySQL query looks right now -

SELECT * FROM tableName WHERE columnName REGEXP "^[a-zA-Z]{3}someString";
5
  • Do you want a PHP expression or a MySQL expression? Commented Jun 29, 2012 at 16:02
  • I need MySQL expression. Commented Jun 29, 2012 at 16:06
  • why would you not substr the required letters with php and do the "Select * From Table Where coloumn LIKE '$string%'" ?? Commented Jun 29, 2012 at 16:18
  • Why substring when you could LEFT(string, 3)? Commented Jun 29, 2012 at 16:19
  • yeah Left is fine - use whichever is faster if that matters :) - I just gave another idea without using regular expression Commented Jun 29, 2012 at 16:21

2 Answers 2

4

You cannot use CONCAT or alike with REGEX, it will fail. Easiest way to do it, is:

$query = 'SELECT * FROM Test WHERE colb REGEXP "^'.substr($mystring,0,3).'"');

Another is:

SELECT * FROM Test WHERE LEFT(colb, 3) LIKE "{$mystring}%"
Sign up to request clarification or add additional context in comments.

Comments

-3

Please use jQuery and jqSQL plugin. Note that symbol $ must be escaped in SQL query with this plugin.

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.