Varinder Sohal
Varinder Sohal

Reputation: 1292

How to get data from database with specific combination of name

I am working on ruby on rails project and I need to get data from the database with a specific combination like c*_c*_othername * can be numbered 1,2,3 etc like c1_c1_anystring. Prefix c is fixed for all time. I am trying with following code but it's not working

Topic.where("name like ?", "%c*_c*_*%")

Upvotes: 0

Views: 79

Answers (2)

user11350468
user11350468

Reputation: 1407

You might need SIMILAR TO

Try the below:

Topic.where('name SIMILAR TO ?', "%c\\d\\_c\\d\\_%")

If you are accepting more than one digits, Use the below pattern

Topic.where('name SIMILAR TO ?', "%c\\d+\\_c\\d+\\_%")

If you don't like escaping underscores, You can also use ~ for pattern matching as mentioned in the docs:

Topic.where('name ~ ?', ".*c\\d+_c\\d+_.*")

\d in the regular expression matches digits from 0 to 9

c*_c*_othername the othername is not compulsory. Some time the name is c5_c6 only so this type of names I also want to get

Please try the below pattern

 Topic.where('name ~ ?', ".*c\\d+_c\\d+(_.*)?$")

Upvotes: 1

Ninh Le
Ninh Le

Reputation: 1331

You can try

Topic.where("name like 'c_\\_c_\\_%'")

Upvotes: 0

Related Questions