0

I'm using Rails/ActiveRecord/Postgres. Here is a sample test string I'm trying to match -

:sample_data => "$$352054054640611,1010,2015/02/24,05:20:30,40.28370,-111.65530,1437.1,0,0,0,0,0.0,7,0.9,1010,0.0,12.2,8,1,0,81.3##"

I only want to query for the first number after the first comma (ex: 1010). In Rails I was looking to do something like this.

number = "1010"
Model.where("sample_data ~* ?", "\$\$.*," + number + ",.*")

The problem is it looks like Postgres isn't allowing me to escape the two dollar signs like I hoped.


Edit

When I run Model.where("sample_data ~* ?", "\$\$.*," + number + ",.*").to_sql

I get -

"SELECT \"Model\".* FROM \"Model\"  WHERE (sample_data ~* '$$.*,1010,.*')"
4
  • Can you add the result of Model.where("sample_data ~* ?", "\$\$.*," + number + ",.*").to_sql Commented Feb 10, 2016 at 19:52
  • @max I updated my question with the result Commented Feb 10, 2016 at 19:57
  • 1
    Hmm, maybe you need to double escape? Model.where("sample_data ~* ?", "\\$\\$.*," + number + ",.*") Commented Feb 10, 2016 at 20:00
  • @max the double escapes work! The problem I'm having now is match the first set of digits - Model.where("sample_data ~* ?", "\\$\\$(\\c+),1010,.*") Commented Feb 10, 2016 at 20:17

1 Answer 1

2

The answer to your question is, you need escape the backslashes. You're wanting to pass them in to Postgres, but Ruby is escaping the dollars instead. (It doesn't need to, because '$' isn't a special character in a Ruby string, but it'll let you do it anyway.)

Model.where("sample_data ~* ?", "\\$\\$.*," + number + ",.*").to_sql

The answer to your problem is, you probably don't need to specify the dollars at all. Try this:

Model.where("sample_data ~* ?", "^[^,]*,#{number}").to_sql

To help you interpret this regex:

  • ^ = start of line
  • [^,] = any character other than a comma
  • * = zero to many times

This will also ensure that you don't find your number after a comma that isn't the first.

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.