user3622734
user3622734

Reputation: 3

Regex to match first n characters of a string

I am creating a regex to query a MySQL database dynamically based on some text. I have the text parsed, and now I need to make a regex based off of the text that will match a string that contains the first N characters of the text with a minimum of 3 characters. So far I am doing this:

var regex = new RegExp('^' + text.substr(0, 3).replace(/[[\]{}()*+?.\\|^$\-,&#\s]/g, '\\$&'));

That works to make sure the first three characters match, but then I want to query the database to see if there are any matches for the rest of the text. For example, if the text was 'test string', I want to make a regex that will match columns in the database with values such as 'tes', 'test str', 'test string', etc. only up to as far as the text goes.

I wasn't really sure how to word the title, so hopefully I did not miss any similiar questions. If there is a better way to query the database for this, I am open to that too.

Upvotes: 0

Views: 1260

Answers (1)

Demian
Demian

Reputation: 46

In plain MySQL you could write:

select * from table where column like concat(left(@YOUR_INPUT, 3),  '%') and instr(@YOUR_INPUT, column);  

where @YOUR_INPUT would be the full text value you have in hand (whether you pass it as a parameter [which is the proper way :) ] to the query or you put it in a MySQL variable).

edited: Added a clause to ensure that only matches the strings that are contained within the input and not the others

Upvotes: 1

Related Questions