Rails SQL regular expression

后端 未结 3 939
粉色の甜心
粉色の甜心 2020-12-28 12:39

I\'m trying to search for the maximum number in the series A0001, A0002, A1234, A2351, etc... The problem is that the list I\'m searching in also has strings such as AG1089

3条回答
  •  情书的邮戳
    2020-12-28 12:53

    On Rails 4+ with a Postgres database the general form of a RegEx query is:

    Model.where("column ~* ?", 'regex')
    

    As for the regex, it can be a general '^A\d+$' or more specific '^A\d{4}$' Breaking it down:

    ^ - string start anchor
    A - literal "A"
    \d+ - one or more digits (0-9)
    \d{4} - exactly four digits
    $ - string end anchor
    

    Basically, the regex reads "the string should start with an A, followed by four digits and then the string should end". The final query line is:

    @max_draw = Drawing.where("drawing_number ~* ?", '^A\d{4}$')
    

    Further reading on ruby RegEx at RubyDoc or the more accessible Perl variant (used by Sublime text)

提交回复
热议问题