Rails SQL regular expression

后端 未结 3 931
粉色の甜心
粉色の甜心 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 13:01

    You can't use regular expressions in SQL which is what you're trying to do. Your best bet would be to select just the entries that start with A like your original code, then skip entries that have more than one letter at the beginning.

    items = Drawing.where( [ 'drawing_number LIKE ?' , 'A%' ] )
    max_value = 0
    items.each do |item|
      next if item.drawing_number =~ /\A[A-Za-z]{2,}/
      drawing_number = item.drawing_number.gsub(/\AA/, '').to_i
      max_value = drawing_number if drawing_number > max_value
    end
    

    I'm reasonably certain it's possible to get this shorter but this should do what you need.

    (\A is the start of line anchor that works with strings containing newlines)

    ({2,} matches two or more of the proceeding character range)

    http://www.rubular.com/ is awesome for testing ruby regexes.

提交回复
热议问题