Is there a way of changing regular expressions to a range of numbers in Ruby on Rails?

后端 未结 2 755
离开以前
离开以前 2021-01-27 17:04

I often need to create range of numbers in regular expressions. So e.g. \'[2-3][0-9]\' is range of numbers between 20-39. To double check my range, I normally use Linux command.

相关标签:
2条回答
  • 2021-01-27 17:41

    Using a regex to see if a number is in a certain range is code smell in the first place. You are taking the wrong approach (unless you are doing code golf or some other hacky thing). You should not try to build a regex that is intended to match a number in a certain range.

    I recommend you not to use a regex for the checking part. Rather, just extract the number as is (using a regex), and see if it is within a range in a more direct way. Suppose you have a string s. Extract the number part of it using (\d+) within a regex . Then take out that part (if it is the first parenthesis in the regex, then it is $1), convert it into a number, and check if it fits in the range.

    (20..39).cover?($1.to_i)
    
    0 讨论(0)
  • 2021-01-27 17:57

    You should write a unit test if you're concerned about it.

    To test your regex quickly, use irb and write plain old Ruby:

    irb(main):005:0> (1..40).map(&:to_s).grep(/[2-3][0-9]/)
    => ["20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39"]
    

    That said, there are far better ways of producing ranges of numbers than filtering a whole sequence through a regular expression. That might, in fact, be the worst way of doing so.

    (20..39).to_a
    

    or

    20.upto(39).to_a
    

    or

    20.times.map { |i| 20 + i }
    

    And many, many, many more. They're all infinitely better than using a regex to filter down a larger set of numbers to only those you need in order to build a simple sequential range.

    0 讨论(0)
提交回复
热议问题