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

后端 未结 2 754
离开以前
离开以前 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)
    

提交回复
热议问题