Home > OS >  Activerecord query with regex
Activerecord query with regex

Time:06-30

I need to find all the records which contains the given sub-string(art), and the condition is the given substring is either a complete word within the string or the start of any word within the string.

Sample data. Program

id | name
-----------
10 | Report of Quarter 1
11 | The Art Program
12 | The Artificial Program

From the above data, I must be able to get the record numbers 11 and 12 but not 10.

I am trying like this

Program.where("name ~* ?",'art\b') but it's not working

I have also tried with Program.where("regexp_match(name, ?)",'/art\b/i') this too is not working

any help is really appreciable. Thanks!

CodePudding user response:

I guess you are using Postgres since you gave an example with regexp_match

Try Program.where("name ~* ?",'art\M') :)

You can see hidden in the Postgres docs ("Regular Expression Escapes" section) that \b means "backspace, as in C" whereas \M "matches only at the end of a word"

  • Related